2

Given this piece of code, how do i know using "i" variable that the method wasn't derived from base classes, but it was declared in the most downcasted class? For example, i don't need no GetType(), ToString() etc and so forth methods to be printed about.

MethodInfo[] methods = Type.GetType(
            "Probabilities_Theory.ProbabilitiesTheory").GetMethods();

foreach (var i in methods)
{
    if (!i.IsVirtual) // another condition needed
        Console.WriteLine(i);
}

I don't need to know if it was overriden or not, because for example GetType() method is not virtual for the reason. But i still don't want GetType() to be printed about.

What's common in GetType() and the other methods that are virtual is that they all weren't declared in the most downcasted class.

I could do it this way:

if (i.DeclaringType == typeof(ProbabilitiesTheory))
    Console.WriteLine(i);

But i want my code to be more automatic, more programmic and stuff. Like one doesn't know what type it is.

  • That sounsd like it could be a XY Problem https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem But for me, any use of Reflection does. Usually you just figure that out by downcasting the type. Then you do know. – Christopher Nov 25 '18 at 17:45
  • Check the properties of `MethodInfo`. There should be one telling which type declared that method. –  Nov 25 '18 at 17:46
  • Possible duplicate of [Detect if a method was overridden using Reflection (C#)](https://stackoverflow.com/questions/2932421/detect-if-a-method-was-overridden-using-reflection-c) – Alexander Pope Nov 25 '18 at 17:47

1 Answers1

1

Try with BindingFlags.DeclaredOnly:

MethodInfo[] methods = Type.GetType("Probabilities_Theory.ProbabilitiesTheory")
                           .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Pragmateek
  • 13,174
  • 9
  • 74
  • 108