我正在尝试实现一个允许输出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 :(得分:8)
像这样:
object value = info.GetValue(item, null);
答案 1 :(得分:1)
你去..
PropertyInfo[] propertyInfo = item.GetType().GetProperties();
var val = propertyInfo.GetValue(item, null);