【问题标题】:Reflection and Generics get value of property反射和泛型获得属性的价值
【发布时间】:2010-04-29 13:27:34
【问题描述】:

我正在尝试实现一个允许输出 csv 文件的通用方法

public static void WriteToCsv<T>(List<T> list) where T : new()
    {
        const string attachment = "attachment; filename=PersonList.csv";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.AddHeader("Pragma", "public");                   

        bool isFirstRow = true;
        foreach (T item in list)
        {                
            //Get public properties
            PropertyInfo[] propertyInfo = item.GetType().GetProperties();

            while (isFirstRow)
            {
                WriteColumnName(propertyInfo);
                isFirstRow = false;
            }

            Type type = typeof (T);

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PropertyInfo info in propertyInfo)
            {
                   //string value ???? I am trying to get the value of the property info for the item object

            }                
            HttpContext.Current.Response.Write(stringBuilder.ToString());
            HttpContext.Current.Response.Write(Environment.NewLine);                
        }
        HttpContext.Current.Response.End();
    }

但我无法获取对象属性的值

有什么建议吗?

谢谢

【问题讨论】:

  • 请记住,这里有一些边界情况,例如索引器属性。简单的 GetValue 调用将引发索引器属性,因此您必须决定是否要显式忽略它们(可以检查索引器参数的数量是否为 0)或以其他方式处理它们。根据您的应用程序,您可能还希望以不同的方式处理 Nullable 属性。

标签: c# .net asp.net generics reflection


【解决方案1】:

像这样:

object value = info.GetValue(item, null);

【讨论】:

    【解决方案2】:

    给你..

    PropertyInfo[] propertyInfo = item.GetType().GetProperties(); 
    var val = propertyInfo.GetValue(item, null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      相关资源
      最近更新 更多