In .NET, can you use reflection to get all non-inherited methods of a class?

梦想与她 提交于 2019-12-21 06:57:28

问题


Because of this issue here, I'm trying to write a custom JsonConverter that handles cases where you subclass a list or a collection, then add extra properties to it. As such, one approach would be to ignore all base-class properties and only serialize those in the defined class. (Technically this won't work because if you subclass that subclass you break the serialization, but it did make me wonder...)

Is it possible via reflection (well I know the answer is 'yes' because Reflector does exactly that, but I don't know how) to get only the members that are defined on the class itself as opposed to those that were inherited? For instance...

public class MyBaseClass
{
    public string BaseProp1 { get; set; }
    public string BaseProp2 { get; set; }
}

public class MySubClass : MyBaseClass
{
    public string SubProp1 { get; set; }
    public string SubProp2 { get; set; }
}

In this case, I want to reflect on MySubClass and only get SubProp1 and SubProp2 while ignoring BaseProp1 and BaseProp2. So can that be how is that done?

M


回答1:


While calling "GetMembers" method to get the members of the Type, you can specify "DeclaredOnly" in binding flag.




回答2:


You have to select all members in MySubClass and keep only those where DeclaringType == MySubClass.

With LINQ, something like that (overkill) :

MemberInfo[] notInherited = GetType("MySubClass").GetMembers().Where(m => m.DeclaringType == GetType("MySubClass"));

Or with GetMembers() overload :

MemberInfo[] notInherited = GetType("MySubClass").GetMembers(BindingFlags.DeclaredOnly);



回答3:


A lot of reflection functions accept a parameter of type BindingFlags. This enumeration includes a value DeclaredOnly:

Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.




回答4:


MemberInfo.DeclaringType should do what you need. To get members directly defined in type X filter the members by DeclaringType == typeof(X).



来源:https://stackoverflow.com/questions/5880819/in-net-can-you-use-reflection-to-get-all-non-inherited-methods-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!