[英]How to get value of inherited property using reflection?
如何使用反射獲取繼承的屬性值? 我嘗試使用BindingFlags
但仍然觸發NullReferenceException
object val = targetObject.GetType().GetProperty("position", BindingFlags.FlattenHierarchy).GetValue(targetObject, null);
position
是公共財產,具有聲明價值。
編輯:
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);
我嘗試了幾種與BindingFlags的組合,但是p
總是為null :(,
如果您使用BindingFlags
重載,則必須明確指定您感興趣的所有標志。
另請注意:(來自MSDN )
您必須指定BindingFlags.Instance或BindingFlags.Static才能獲得返回。
object val = targetObject.GetType()
.GetProperty("position",
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.Public)
.GetValue(targetObject, null);
編輯:
你有一個position
領域而不是財產 !
(一個開始學習差異的好地方: C#3.0+中屬性和字段之間的差異,尤其是這個答案 )
將您的position
更改為財產:
public float[] position { get; set; }
或者使用targetObject.GetType().GetField(...
方法來檢索字段。
BindingFlags.FlattenHierarchy
僅適用於靜態成員。 一定要指定
BindingFlags.Instance | BindingFlags.Public
你應該得到繼承的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.