反射属性值记录

狂风中的少年 提交于 2020-03-12 06:54:23
 1  /// <summary>  
 2         /// 通过遍历属性输出属性和值  
 3         /// </summary>  
 4         /// <param name="item"></param>  
 5         public IList<ActionModelPropertyModel> GetProperty<T>(T item)
 6         {
 7 
 8             System.Reflection.PropertyInfo[] properties = item.GetType().GetProperties();
 9             var data = from propertyInfo in properties
10                        select new ActionModelPropertyModel()
11                        {
12 
13                            PropertyName = propertyInfo.Name,
14                            PropertyValue = propertyInfo.GetValue(item).ToString(),
15                            PropertyType = propertyInfo.PropertyType.ToString()
16                        };
17             return data.ToList();
18         }
19         /// <summary>
20         /// todo 在Type实例化之前是没有Value的
21         /// </summary>
22         /// <param name="item"></param>
23         /// <returns></returns>
24         public IList<ActionModelPropertyModel> GetProperty(Type item)
25         {
26             System.Reflection.PropertyInfo[] properties = item.GetProperties();
27             var data = from property in properties
28                        select new ActionModelPropertyModel()
29                        {
30                            PropertyName = property.Name,
31                            PropertyValue = "",
32                            PropertyType = property.PropertyType.Name,
33                            
34                        };
35 
36             return data.ToList();
37         }

调了一小时,老是报System.Reflection.TargetException:“对象与目标类型不匹配。”

 propertyInfo.GetValue(item).ToString(),没实例化何来的值,博客园的处女文章,欢迎指正

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