簡體   English   中英

類型參數對象的訪問屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM