.NET获得通过反射私有财产反射、财产、NET

2023-09-04 11:35:09 作者:野浪

我有以下情形

Assebly A

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

}

组件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; }
    }
}    

在类MyBaseEntity我试图让私人的ISet儿童和调用方法添加。 我所说的的addChild方法,像

In the class MyBaseEntity I try to get the private ISet child and call the method "Add". I call the "addChild" method like

myObject.addChild<MyModelChild>(child);

的GetProperties,方法不提取私有财产。它可以提取所有的公共属性,而不是私人的。

but the GetProperties method doesn't extract the private property. It can extracts all the public properties but not the private.

任何人都可以帮我吗?

感谢您!

推荐答案

这两个士兵你指的是字段,而不是属性,当然,你不会找到他们的 的GetProperties, (可以使用的 GetFields 为)。

The two privates you refer to are fields, not properties, naturally you won't find them with GetProperties (you can use GetFields for that).