How to get methods in a type

Note: an instance of System.Type.

The goal is to get the methods introduced (I don't know the right word) in a type that - not inherited - is not overridden

I want to use .NET Reflection, and I tried the Type.GetMethods() method. But he returned even inherited and redefined.

I was thinking about filtering after getting all the methods. And I looked at the properties / methods set by the MethodInfo class. I could not figure out how to get what I wanted.

For example: I have a class, class A { void Foo() { } }

When I call typeof(A).GetMethods() , I get Foo along with the methods in System.Object : Equals , ToString , GetType and GetHashCode . I want to filter it only to Foo .

Does anyone know how to do this?

Thanks.

+6
source share
4 answers

GetMethods has an overload that allows you to specify BindingFlags . For instance. therefore, if you need to get all declared public instance methods, you need to pass the appropriate flags.

 var declaredPublicInstanceMethods = typeof(A).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); 
+8
source

I hope that was what you want

 var methods = typeof(MyType).GetMethods(System.Reflection.BindingFlags.DeclaredOnly); 
+2
source

try it

 typeof(Foo).GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly) 

http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

http://msdn.microsoft.com/en-us/library/4d848zkb.aspx

+1
source

You can filter the returned MethodInfo collection using DeclaringType:

 var methods = typeof(A).GetMethods().Where(mi => mi.DeclaringType== typeof(A)); 
0
source

Source: https://habr.com/ru/post/909691/


All Articles