[英]How to get value of property from object of class at runtime using reflection
我有一個類如下:
Class A : B<C>
{
public A(C entity):base(entity)
{}
}
abstract class B<T>
{
public B(T entity)
{
Entity = entity;
}
public T Entity { get; private set; }
}
Class C: D
{
public string prop2{get;set;}
}
Class D
{
public string prop1{get;set;}
}
Main()
{
A obj = new A(new C());
obj.GetType().GetProperty("prop1", BindingsFlag.Instance|BindingsFlag.FlatteredHierarchy)// is null
}
我有類A的對象。我想在運行時從這個對象獲取屬性值。
我正在努力
obj.GetType().GetProprty("propertyName",
BindingsFlag.FlattenHierarchy).GetValue(obj, null);
但是,GetProprty()正在返回null,因為該屬性在D或C類中聲明。
有人可以建議我如何實現這一目標嗎?
提前致謝。
GetType().GetProperty("propertyName", BindingsFlag.FlattenHierarchy)
.GetValue(obj, null);
您正在錯誤地指定wheter get實例或靜態屬性的綁定標志:
BindingsFlag.FlattenHierarchy | BindingsFlag.Instance
根據MSDN標志BindingsFlag.Instance
或BindingsFlag.Static
必須明確指定才能獲得非null值:
您必須指定BindingFlags.Instance或BindingFlags.Static才能獲得返回。
更重要的是,默認情況下public
財產被排除在外。 因此,如果您的屬性是public
,則需要指定其他標志:
BindingsFlag.FlattenHierarchy | BindingsFlag.Instance | BindingsFlag.Public
備注:
指定BindingFlags.Public以在搜索中包含公共屬性。
如果base中的屬性是私有的, FlattenHierarchy
將不會枚舉它:
(...)未包含繼承類中的私有靜態成員如果是這種情況,我擔心您必須手動遍歷基類並搜索該屬性。
確保該屬性名稱有效且存在。
編輯:編輯后,我看到了問題。 你的A類不是D類的子類(你想從D類獲得屬性)。 這就是為什么獲得財產價值不是這樣的。 您需要按照以下步驟操作:
// get entity prop value
var entityValue =
(obj.GetType()
.GetProperty("Entity",
BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public)
.GetValue(obj));
// get prop value
var prop1Value =
entityValue.GetType()
.GetProperty("prop1",
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.Public)
.GetValue(entityValue);
記得處理空值等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.