The use of generics and reflection to achieve the transformation of the force. The code is doped with detailed comments, a little bit about generics and reflection to understand the nature of the transformation. Can be directly copied and pasted to invoke OH.
Public classDtconvertolist<t>whereT:New(){ Public StaticList<t>dttolist (DataTable dt) {//Defining CollectionsList<t> listcollection =NewList<t>(dt. Rows.Count); //get T Model typeType T_type =typeof(T); //get T Model type public propertiespropertyinfo[] Proper =T_type. GetProperties (); //temporary variables, storage variables model public properties name stringTempname =""; //iterate through each row of the parameter DataTable foreach(DataRow Drinchdt. Rows) {//instantiate a T template classT t =NewT (); //traverse the various properties of the T-template class #region foreach(PropertyInfo PinchProper) { //remove one of the class propertiesTempname =P.name; //determine if this column is in a DataTable if(dt. Columns.contains (Tempname)) {//to determine whether a property is writable property if(!p.canwrite) { Continue; } Try { //get the value in cell datable ObjectValue =Dr[tempname]; //Get the T attribute typeType Protype =P.propertytype; //Judging type Assignment if(Value! =dbnull.value) {// if(value.) GetType () = =Protype) {P.setvalue (t, value,NULL); } Else { if(Protype = =typeof(string)) { stringTemp =value. ToString (); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof(byte)) { byteTemp =Convert.tobyte (value); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof( Short)) { ShortTemp = Short. Parse (value. ToString ()); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof(Long)) { LongTemp =Long. Parse (value. ToString ()); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof(Int64)) {Int64 Temp=Convert.toint64 (value); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof(Int32)) {Int32 Temp=Convert.ToInt32 (value); P.setvalue (t, Temp,NULL); } Else if(Protype = =typeof(Int16)) {Int16 Temp=convert.toint16 (value); P.setvalue (t, Temp,NULL); } Else { ObjectTemp =Convert.changetype (value, Protype); P.setvalue (t, Temp,NULL); } } } } Catch(Exception) {Throw; } } } #endregionListcollection.add (t); } returnlistcollection; }}
View Code
C # DataTable converted to list<t>