反射(C#基础回顾04)

昨天在项目中接触到了反射,下面简单梳理一下;

Reflection---反射

命名空间:

using System.Reflection;

下面上一段简单应用,datatable转List<T>

 1 public static List<T> DtToList<T>(DataTable dt)
 2 {
 3     Type type = typeof(T);
 4     //反射获取对象类属性名
 5     PropertyInfo[] propertyInfos = type.GetType().GetProperties();
 6     List<T> list = new List<T>();
 7     //遍历行
 8     foreach (DataRow dr in dt.Rows)
 9     {
10         T model = Activator.CreateInstance<T>();
11         //遍历列
12         foreach (DataColumn dc in dt.Columns)
13         {
14             string cn = dc.ColumnName;
15             string val = dr[cn].ToString();
16             //找出与dt列名相同的类属性名,并赋值
17             propertyInfos.Where(a=>a.Name== cn).First().SetValue(model, val);
18         }
19         list.Add(model);
20     }
21     return list;
22 }

 

posted @ 2019-04-02 09:22  Crazydragcool  阅读(132)  评论(0编辑  收藏  举报