反思与泛型得到的属性值 [英] Reflection and Generics get value of property
本文介绍了反思与泛型得到的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现一个通用的方法,可以输出CSV文件
i am trying to implement a generic method which allows to output csv file
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();
}
但我不能够获得对象的属性值
but I am not able to get the value of the object's property
任何建议?
感谢
推荐答案
这样的:
object value = info.GetValue(item, null);
这篇关于反思与泛型得到的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文