![](/img/trans.png)
[英]How can I access property on object of type T, when T is a generic class with unknown parameter?
[英]access property of type parameter object
我正在使用以下代碼
public static void SaveArrayAsCSV<T>(T[] arrayToSave, string fileName)
{
using (StreamWriter file = new StreamWriter(fileName))
{
foreach (T item in arrayToSave)
{
//item.GetType().GetField("AccountName")
//item.GetType().GetProperty("AccountName")
file.WriteLine(item + ",");
}
}
}
此處,該項目具有名為AccountName
屬性,
我試圖使用訪問它
item.GetType().GetField("AccountName") //returns null
item.GetType().GetProperty("AccountName") //returns an object, not able to spot the actual value in it
但是兩者都沒有返回值。 但是當我使用快速手表檢查時,我可以看到物業
您需要使用GetValue
方法,請嘗試以下操作:
var accountName = item.GetType().GetProperty("AccountName").GetValue(item);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.