[英]Get a list via reflection
我有一些類包含一個PropertyInfo類型的List:
public List<PropertyInfo> Properties {get; set;}
我有一個該類的實例,但不知道它在運行時是哪個類。 所以對於那個實例,在我的情況下,它被稱為P
,我需要遍歷上面提到的列表。 現在我可以使用以下方法獲取屬性的值:
var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)
但是,如果我嘗試循環它:
foreach (var thisProp in PropList) - I get an error.
那么,有沒有其他方法可以做到這一點?
謝謝
你必須施放 :
var PropList = P
.GetType()
.GetProperty("Properties")
.GetValue(P, null) as IEnumerable<PropertyInfo>; // notice "as ..."
// Since PropList is IEnumerable<T> you can loop over it
foreach (var thisProp in PropList) {
...
}
因為GetValue(...)
單獨返回object
。
在查看您的代碼后,很明顯
var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)
因為你得到的錯誤而沒有返回一個不可數的。 一種可能的解決方案要解決此問題,您需要將其強制轉換為Ienumerable。
var PropList = P
.GetType()
.GetProperty("Properties")
.GetValue(this, null) as IEnumerable<PropertyInfo>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.