2010-04-29 37 views
2

我想实现一个通用的方法,它允许输出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(); 
    } 

价值,但我不能获得对象的属性

任何建议的价值?

感谢

+0

记住,有一些边界情况在这里,如索引属性。简单的GetValue调用会抛出一个索引器属性,因此您必须决定是否要显式忽略它们(可以检查索引器参数的数目是否为0)或以其他方式处理它们。根据您的应用程序,您可能也想要以不同的方式处理Nullable属性。 – 2010-04-29 13:51:12

回答

6

像这样:

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

在这里,你去..

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