简体   繁体   English

.NET通过Reflection获取私有财产

[英].NET Get private property via Reflection

I've the following scenario 我有以下情况

Assebly A 安装A

public abstract class MyBaseEntity        
{   
    //Uncompleted method     
    public void addChild<T>(T child)
    {            

        try
        {                
            Type tInfo = this.GetType();
            PropertyInfo pInfo = tInfo.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).Where(p => p.PropertyType == typeof(ISet<T>)).FirstOrDefault();                
            MethodInfo mInfo = tInfo.GetMethod("Add");
            mInfo.Invoke(this, new object[] {child});
        }
        catch (Exception ex)
        {               
            throw ex;
        }
    }

}

Assembly B 大会B.

 public class MyModel : MyBaseEntity
{
    public virtual int p1 { get; set; }
    public virtual int p2 { get; set; }
    public virtual DateTime p3 { get; set; }
    public virtual bool p4 { get; set; }
    private readonly ISet<MyModelChild> _p5;
    private readonly ISet<MyModelChild2> _p6;
    public virtual string p7 { get; set; }

    public MyModel()
    {
        this._p5 = new HashSet<MyModelChild>();
        this._p6 = new HashSet<MyModelChild2>();
    }

    public virtual IEnumerable<MyModelChild> P5
    {
        get { return _p5; }
    }

    public virtual IEnumerable<MyModelChild2> P6
    {
        get { return _p6; }
    }
}    

In the class MyBaseEntity I try to get the private ISet child and call the method "Add". 在MyBaseEntity类中,我尝试获取私有ISet子节点并调用方法“Add”。 I call the "addChild" method like 我称之为“addChild”方法

myObject.addChild<MyModelChild>(child);

but the GetProperties method doesn't extract the private property. GetProperties方法不提取私有属性。 It can extracts all the public properties but not the private. 它可以提取所有公共属性,但不提取私有属性。

Anyone can help me? 有人可以帮帮我吗?

Thank you! 谢谢!

你引用的两个私有字段是字段,而不是属性,当然你不会用GetProperties找到它们(你可以使用GetFields )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM