Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Get private property via Reflection

I've the following scenario

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

}

Assembly 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". I call the "addChild" method like

myObject.addChild<MyModelChild>(child);

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

Anyone can help me?

Thank you!

like image 280
Faber Avatar asked Dec 19 '11 18:12

Faber


1 Answers

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

like image 165
diggingforfire Avatar answered Oct 18 '22 09:10

diggingforfire