In the case of an entity conversion operation, if you need to make a conversion between two entities with the same class of two attribute fields, we want to copy the values of all the fields of the A object to the B object, we can only use B. property = A. property to write, if there are too many attribute fields, it is necessary to write a lot of line copy statements, the trouble is also easy to miss some, this time can be used in C # reflection to achieve replication. We can write a mapping function that takes advantage of generics.
1. For creating entities, assign values from one entity as a data source
/// <summary> ///reflection implements a copy of the value of the same property between objects of two classes///suitable for initializing new entities/// </summary> /// <typeparam name= "D" >the returned entity</typeparam> /// <typeparam name= "S" >Data Source Entity</typeparam> /// <param name= "S" >Data Source Entity</param> /// <returns>the new entity returned</returns> Public StaticD Mapper<d, s>(s s) {D d= Activator.createinstance<d> ();//constructing a new instance Try { varTypes = S.gettype ();//Get Type varTyped =typeof(D); foreach(PropertyInfo SPinchTypes.getproperties ())//Get property fields of type { foreach(PropertyInfo DPinchtyped.getproperties ()) { if(DP. Name = = sp. Name && DP. PropertyType = = sp. PropertyType && DP. name!="Error"&& DP. Name! ="Item")//determine if property names are the same{dp. SetValue (d, Sp.) GetValue (s),NULL),NULL);//gets the value of the S object property copied to the properties of the D object } } } } Catch(Exception ex) {Throwex; } returnD; }
2. Applicable to the conversion of data between two entities without creating an entity
/// <summary> ///reflection implements a copy of the value of the same property between objects of two classes///applies to no new entities between/// </summary> /// <typeparam name= "D" >the returned entity</typeparam> /// <typeparam name= "S" >Data Source Entity</typeparam> /// <param name= "D" >the returned entity</param> /// <param name= "S" >Data Source Entity</param> /// <returns></returns> Public StaticD Mappertomodel<d, s>(D d,s S) {Try { varTypes = S.gettype ();//Get Type varTyped =typeof(D); foreach(PropertyInfo SPinchTypes.getproperties ())//Get property fields of type { foreach(PropertyInfo DPinchtyped.getproperties ()) { if(DP. Name = = sp. Name && DP. PropertyType = = sp. PropertyType && DP. Name! ="Error"&& DP. Name! ="Item")//determine if property names are the same{dp. SetValue (d, Sp.) GetValue (s),NULL),NULL);//gets the value of the S object property copied to the properties of the D object } } } } Catch(Exception ex) {Throwex; } returnD; }
C # Replication of values that implement the same property between objects of two classes with reflection