Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of inherited property using reflection?

Tags:

c#

reflection

How to get inherited property value using reflection? I try with BindingFlags but still trigger NullReferenceException

object val = targetObject.GetType().GetProperty("position", BindingFlags.FlattenHierarchy).GetValue(targetObject, null);

position is iherited public property and has a declared value.

EDIT:

class myParent
{
    public float[] position;
    public myParent()
    {
        this.position = new float[] { 1, 2, 3 };
    }
}

class myChild : myParent
{
    public myChild() : base() { }
}

myChild obj = new myChild();
PropertyInfo p = obj.GetType().GetProperty("position", BindingFlags.Instance | BindingFlags.Public); 

I tried with several combinations with BindingFlags but p always is null :( ,

like image 447
abuduba Avatar asked Sep 08 '12 11:09

abuduba


1 Answers

BindingFlags.FlattenHierarchy

works only for static members. Be sure to specify

BindingFlags.Instance | BindingFlags.Public

and you should get inherited properties.

like image 193
armen.shimoon Avatar answered Sep 24 '22 03:09

armen.shimoon