1 public static list <t> getlist <t> (datatable table) where T: New () 2 {3 list <t> List = new list <t> (); 4 // 5 t = default (t); 6 propertyinfo [] propertypes = NULL; 7 string tempname = string. empty; 8 Try 9 {10 foreach (datarow row in table. rows) 11 {12 // dynamically create object 13 T = activator. createinstance <t> (); 14 t = new T (); 15 propertypes = T. getType (). getproperties (); 16 foreach (propertyinfo pro in propertypes) 17 {18 tempname = pro. Name; 19 if (table. Columns. Contains (tempname) 20 {21 object value = row [tempname]; 22 if (value! = NULL & value! = Dbnull. Value & Row [tempname]. tostring ()! = NULL & 23! Row [tempname]. tostring (). trim (). equals ("") 24 {25 if (tempname. trim (). tolower (). equals ("lastmodify") 26 {27 // pro. setvalue (T, converthelper. converttotimestamp (convert. tostring (value), null); 28} 29 else30 {31 if (Pro. propertytype = typeof (system. char) | Pro. propertytype = typeof (system. nullable <system. char>) 32 {33 pro. setvalue (T, convert. tochar (value), null); 34} 35 else36 {37 pro. setvalue (T, value, null); 38} 39 40 41} 42} 43} 44} 45 list. add (t); 46} 47} 48 catch (exception ex) 49 {50 throw new exception (ex. message); 51} 52 return list; 53}View code
1. t = default (t); indicates that the T type is obtained.
2. t = activator. createinstance <t> (); create an object based on the Type
3. Obtain all attributes
Propertypes = T. GetType (). getproperties ();
4. Pro. setvalue (T, value, null); set the attribute value of the corresponding object
Converts a DataSet object to a list set.