访问类型参数对象的属性

时间:2017-09-29 11:51:32

标签: c#

我正在使用以下代码

 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

但两者都没有返回值。但是,当我使用快速手表检查时,我能够看到该属性

1 个答案:

答案 0 :(得分:1)

您需要使用GetValue方法,试试这个:

var accountName = item.GetType().GetProperty("AccountName").GetValue(item);
相关问题