C # Use reflection to replicate the values of the same attributes between objects of two classes,
During object conversion, if you need to perform conversion between two classes with the same attribute fields, we want to copy the values of all fields of object a to object B. We can only use object B. property =. attribute writing. If there are too many attribute fields, you need to write a lot of row replication statements, which may easily be omitted. In this case, the reflection of c # Can Be Used for replication. We can write such a ing function that uses generics.
1. It applies to assigning values from an object as a data source when creating an object.
/// <Summary> /// reflection copies the values of the same attributes between objects of the two classes. /// applies to initializing new entities. /// </summary> // <typeparam name = "D"> returned entity </typeparam> // <typeparam name = "S"> data source entity </typeparam> // <param name = "s"> data source entity </param> /// new entity returned by <returns> </returns> public static D Mapper <D, s> (S s) {D d = Activator. createInstance <D> (); // create a new instance. try {var Types = s. getType (); // obtain the type var Typed = typeof (D); foreach (PropertyInfo sp in Types. getProper Ties () // obtain the type of attribute field {foreach (PropertyInfo dp in Typed. getProperties () {if (dp. name = sp. name & dp. propertyType = sp. propertyType & dp. name! = "Error" & dp. Name! = "Item") // determines whether the attribute name is the same {dp. setValue (d, sp. getValue (s, null), null); // copy the value of the s object property to the property of the d object }}} catch (Exception ex) {throw ex ;} return d ;}
2. Applicable to the conversion of data between two entities without creating an object
/// <Summary> /// reflection copies the values of the same attributes between objects of the two classes. /// applicable to the absence of newly created entities. /// </summary> /// <typeparam name = "D"> returned entity </typeparam> // <typeparam name = "S"> data source entity </typeparam> /// <param name = "d "> returned entity </param> /// <param name =" s "> data source entity </param> /// <returns> </returns> public static D MapperToModel <d, s> (D d, S s) {try {var Types = s. getType (); // obtain the type var Typed = typeof (D); foreach (PropertyInfo sp in Types. getProperties () // Obtain the type attribute field {foreach (PropertyInfo dp in Typed. getProperties () {if (dp. name = sp. name & dp. propertyType = sp. propertyType & dp. name! = "Error" & dp. Name! = "Item") // determines whether the attribute name is the same {dp. setValue (d, sp. getValue (s, null), null); // copy the value of the s object property to the property of the d object }}} catch (Exception ex) {throw ex ;} return d ;}