Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get methods in a type

Given: System.Type instance.

The aim is to get the newly-introduced methods (i don't know the right word) in the type, which are - not inherited - not overridden

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

I thought of filtering after getting all the methods. And I looked at the properties/methods exposed by MethodInfo class. I could not figure how to get what I wanted.

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

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

Does anyone know how to do this?

Thanks.

like image 341
pnvn Avatar asked Feb 29 '12 23:02

pnvn


People also ask

How to get all methods in a Class c#?

To get the list of methods in class you normally use the GetMethods method. This method will return an array of MethodInfo objects. We have a lot of information about a method in the MethodInfo object and the name is one of them. BindingFlags and MethodInfo enumerations are part of System.

How do you call MethodInfo?

To invoke a static method using its MethodInfo object, pass null for obj . If this method overload is used to invoke an instance constructor, the object supplied for obj is reinitialized; that is, all instance initializers are executed. The return value is null .

What is reflection in programming C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


2 Answers

GetMethods has an overload that lets you specify BindingFlags. E.g. so if you need to get all declared, public, instance methods you need to pass the corresponding flags.

var declaredPublicInstanceMethods = 
    typeof(A).GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
like image 92
Brian Rasmussen Avatar answered Sep 21 '22 08:09

Brian Rasmussen


I hope this was what you want

var methods = typeof(MyType).GetMethods(System.Reflection.BindingFlags.DeclaredOnly);
like image 39
Jalal Avatar answered Sep 21 '22 08:09

Jalal