Class<T> where T:new() 含义

class A<T>  表示A类型接受一种类型,该类型为泛型T,需要运行时传入

where T 表示对类型T的约束关系

new() 表示创建类型T的时候具有构造函数

一般情况下,无法创建一个泛型类型参数的实例。然而,new()约束改变了这种情况,要求类型参数必须提供一个无参数的构造函数

以下是Datable转换为List的一个例子:

 1   public static IList<T> DatableToIList(DataTable dt)
 2         {
 3 
 4             //定义集合
 5             IList<T> list = new List<T>();
 6             foreach (DataRow dr in dt.Rows)
 7             {
 8                 T t = new T();
 9                 PropertyInfo[] properties = t.GetType().GetProperties();
10                 foreach (PropertyInfo pi in properties)
11                 {
12                     
13                     if (dt.Columns.Contains(pi.Name))
14                     {
15 
16                         if (!pi.CanWrite)
17                         {
18                             continue;
19                         }
20                         object value = dr[pi.Name];
21                         if (value!=DBNull.Value)
22                         {
23                             pi.SetValue(t, dr[pi.Name], null);
24                         }
25                       
26                     }
27                 }
28                 list.Add(t);
29             }
30 
31             return list;
32 
33             
34 
35         }

猜你喜欢

转载自www.cnblogs.com/QueryWord/p/12122671.html
今日推荐