How get private properties of Class/BaseClass?

我的未来我决定 提交于 2021-01-28 09:10:15

问题


I use this code:

BindingFlags flags= BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

PropertyInfo prop =  myObj.GetProperty("Age", flags);

prop is not null. However, when I try to get all properties from myObj:

foreach(MemberInfo e in myObj.GetType().GetMembers( flags) ) {    //neither GetProperties helps
    Console.WriteLine(e.Name);
}

that property (Age) is not listed. I can't understand how this happens.


回答1:


The dfiference between Type.GetProperty and Type.GetMembers is that both return private properties/members(which include properties), but GetMembers only of this type and not from base types whereas GetProperty also returns private properties of base types.

GetProperty:

Specify BindingFlags.NonPublic to include non-public properties (that is, private, internal, and protected properties) in the search.

GetMembers:

Specify BindingFlags.NonPublic to include non-public members (that is, private, internal, and protected members) in the search. Only protected and internal members on base classes are returned; private members on base classes are not returned.

So i guess that Age is an inherited property. If you would add BindingFlags.DeclaredOnly the result should be the same, you wouldn't see Age.

If you want to force GetMembers to include also private members of base types, use following extension method that loops all base types:

public static class TypeExtensions
{
    public static MemberInfo[] GetMembersInclPrivateBase(this Type t, BindingFlags flags)
    {
        var memberList = new List<MemberInfo>();
        memberList.AddRange(t.GetMembers(flags));
        Type currentType = t;
        while((currentType = currentType.BaseType) != null)
            memberList.AddRange(currentType.GetMembers(flags));
        return memberList.ToArray();
    }
}

Now your BindingFlags work already and even a private "inherited" Age property is returned:

MemberInfo[] allMembers = myObj.GetType().GetMembersInclPrivateBase(flags);


来源:https://stackoverflow.com/questions/50248686/how-get-private-properties-of-class-baseclass

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