How to get methods in a type
-
14-11-2019 - |
Domanda
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.
Soluzione
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);
Altri suggerimenti
I hope this was what you want
var methods = typeof(MyType).GetMethods(System.Reflection.BindingFlags.DeclaredOnly);
try this
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
You can filter the returned MethodInfo collection by DeclaringType:
var methods = typeof(A).GetMethods().Where(mi => mi.DeclaringType== typeof(A));