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(),没实例化何来的值,博客园的处女文章,欢迎指正
来源:https://www.cnblogs.com/f1516tiger/p/7106467.html