Generic constraints:
1 Public Static ClassTomodel <t>WhereT:Class,New()
Define delegation:
1 Public Delegate VoidSetstring (StringValue );
Delegate creation method:
1 Private StaticSetstring createstringdelegate (T model,StringPropertyname)2 {3Methodinfo MI =Model. GetType (). getproperty (propertyname). getsetmethod ();4Type type =Typeof(Setstring );5ReturnDelegate. createdelegate (type, model, mi)AsSetstring;6}
Use reflection and delegation to convert a able to an object set:
1 Public Static Ilist <t> Getdelegate_tomodellist (datatable DT) 2 { 3 Ilist <t> List = New List <t> (); 4 If (Dt = Null | DT. Rows. Count < 1 ) Return List; 5 Setstring setdelegatestring; 6 Foreach (Datarow Dr In DT. Rows) 7 { 8 T model = New T (); 9 Foreach (Datacolumn DC In DT. columns) 10 { 11 Setdelegatestring = Createstringdelegate (model, DC. columnname ); 12 Setdelegatestring (Dr [DC. columnname]. tostring ()); 13 } 14 List. Add (model ); 15 } 16 Return List; 17 }
In this case, the write problem arises, because the parameter defined by the delegate is of the string type, because we can have the Int or datetime type in the entity, then we need to use the generic delegate.
If the delegate is defined as follows:
1 Public Delegate VoidSetstring <Pt> (PT value)
Create the delegate method (here there is a problem and I do not know how to handle it ):
1 Private Static Setstring Createstringdelegate (T model, String Propertyname) 2 { 3 Methodinfo MI = Model. GetType (). getproperty (propertyname). getsetmethod (); 4 Type type = Typeof (Model). getproperty (propertyname). propertytype; 5 Return Delegate. createdelegate (type, model, mi) As Setstring <type> ; 6 }
Use reflection and delegation to convert a able to an object set:
1 Public Static Ilist <t> Getdelegate_tomodellist (datatable DT) 2 { 3 Ilist <t> List = New List <t> (); 4 If (Dt = Null | DT. Rows. Count < 1 )Return List; 5 Foreach (Datarow Dr In DT. Rows) 6 { 7 T model = New T (); 8 Foreach (Datacolumn DC In DT. columns) 9 { 10 Setstring < Typeof (T). getproperty (DC. columnname). propertytype> setdelegatestring = Createstringdelegate (model, DC. columnname ); 11 Setdelegatestring (Dr [DC. columnname]. tostring ()); 12 } 13 List. Add (model ); 14 } 15 Return List; 16 }
I have been wondering. I hope someone can help me solve this problem. I also have some direct reflection methods, but this problem cannot be solved. I have always had a flaw in my mind. I hope someone can help me. Thank you!