Class <T> where T: new () Meaning

class A <T> represents the type A takes one type, which is a generic type T, the time required to run the incoming

where T represents the constraints of type T

new () to create a type T represents the time has constructors

Under normal circumstances, you can not create an instance of a generic type parameter. However, new new () constraint changed this situation, the request type parameter must provide a no-argument constructor .

The following is an example Datable converted to the 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         }

Guess you like

Origin www.cnblogs.com/QueryWord/p/12122671.html