利用反射的特性将DataReader对象转化为List集合

问题:将SqlDataReader对象转换为List<T>集合

思路:

1,利用反射的特性得到对应实体Model的公共属性

  Type type = typeof(T);  
  PropertyInfo[] p = type.GetProperties();  
这样就得到了该实体Model中的属性  

2,利用反射创建该类的实例

var model = Activator.CreateInstance<T>();  

 3,遍历该实体中的所有属性,将该实例插入到集合中

    整体代码如下:

 1 using System;  
 2 using System.Collections.Generic;  
 3 using System.Reflection;  
 4   
 5 namespace TestService  
 6 {  
 7     public class Test<T> where T:class  
 8     {  
 9         public List<T> GetList(MySql.Data.MySqlClient.MySqlDataReader reader)  
10         {  
11             List<T> list = new List<T>();  
12             Type type = typeof(T);  
13             PropertyInfo[] p = type.GetProperties(); //得到该T类中的所有公共属性
14   
15             while (reader.Read())  
16             {  
17                 var model = Activator.CreateInstance<T>();  
18                 foreach (var item in p)  
19                 {  
20                     if (item == null)  
21                     {  
22                         continue;  
23                     }  
24                     item.SetValue(model, reader[item.Name], null);  
25                 }  
26                 list.Add(model);  
27             }  
28            reader.Close();  
29            return list;  
30         }  
31     }  
32 }  
将不朽的青春献给伟大的编程事业,世界将因我们而改变!
原文地址:https://www.cnblogs.com/luoyefeiwu/p/3458945.html