Reflection and Generics get value of property

社会主义新天地 提交于 2020-01-14 17:51:10

问题


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

Any suggestion?

Thanks


回答1:


Like this:

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



回答2:


Here you go..

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


来源:https://stackoverflow.com/questions/2737663/reflection-and-generics-get-value-of-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!