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 BindingFlags
you have to explicitly specify all the flags what you are interested.
Also note that: (from MSDN )
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return.
object val = targetObject.GetType()
.GetProperty("position",
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.Public)
.GetValue(targetObject, null);
EDIT:
You have a position
field 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 position
to a property:
public float[] position { get; set; }
Or you use the targetObject.GetType().GetField(...
method to retrieve the field.
BindingFlags.FlattenHierarchy
works only for static members. Be sure to specify
BindingFlags.Instance | BindingFlags.Public
and you should get inherited properties.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.