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.
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.
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 .
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.
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);
I hope this was what you want
var methods = typeof(MyType).GetMethods(System.Reflection.BindingFlags.DeclaredOnly);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With