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 🙁 ,
If you use the overload with
BindingFlagsyou have to explicitly specify all the flags what you are interested.Also note that: (from MSDN)
EDIT:
You have a
positionfield not a property !.(A good place to start learning the difference: Difference between Property and Field in C# 3.0+ especially this answer)
Change your
positionto a property:Or you use the
targetObject.GetType().GetField(...method to retrieve the field.