In .NET, can you use reflection to get all non-inh

2019-04-04 00:44发布

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

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-04 00:55

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.

查看更多
闹够了就滚
3楼-- · 2019-04-04 01:01

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

查看更多
该账号已被封号
4楼-- · 2019-04-04 01:03

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);
查看更多
ら.Afraid
5楼-- · 2019-04-04 01:07

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

查看更多
登录 后发表回答