如何获取 Class/BaseClass 的私有属性? [英] How get private properties of Class/BaseClass?

查看:39
本文介绍了如何获取 Class/BaseClass 的私有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码:

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

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

prop 不为空.但是,当我尝试从 myObj 获取所有属性时:

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);
}

该属性 (Age) 未列出.我不明白这是怎么发生的.

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

推荐答案

Type.GetPropertyType.GetMembers 之间的区别在于两者都返回私有属性/成员(其中包括属性),但 GetMembers 只属于这种类型,而不是来自基类型,而 GetProperty 也返回基类型的私有属性.

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:

指定 BindingFlags.NonPublic 以包含非公共属性(即是、私有、内部和受保护的属性)在搜索中.

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

GetMembers:

指定 BindingFlags.NonPublic 以包含非公共成员(即,私有、内部和受保护成员)在搜索中.仅有的返回基类的受保护和内部成员;私人的不返回基类的成员.

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.

所以我猜 Age 是一个继承的属性.如果你添加 BindingFlags.DeclaredOnly 结果应该是一样的,你不会看到 Age.

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.

如果您想强制 GetMembers 也包含基本类型的 private 成员,请使用以下循环所有基本类型的扩展方法:

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();
    }
}

现在你的 BindingFlags 已经工作了,甚至返回了一个私有的继承"Age 属性:

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

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

这篇关于如何获取 Class/BaseClass 的私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆