http://blog.csdn.net/u013093547/article/details/53584591
Today, when copying objects, looking at the code is a bit annoying, a bunch of code, or looking for a direct reflection copy of the same property values of different objects
Baidu a bit, the result of the second blog is that the address is the top link address
The main one is the following code.
1 /// <summary>2 ///Pass in object B of type B, assigning a value of the same name as B to a created3 /// </summary>4 /// <typeparam name= "A" >Type a</typeparam>5 /// <typeparam name= "B" >Type B</typeparam>6 /// <param name= "B" >parameter B of type B</param>7 /// <returns>copy a of the value of the same property in B</returns>8 Public StaticA Mapper<a, b>(b b)9 {TenA = activator.createinstance<a>(); One Try A { -Type TypeB = B.gettype ();//Get Type -Type TypeA =typeof(A); the foreach(PropertyInfo SPinchTypeb.getproperties ())//Get property fields of type - { - foreach(PropertyInfo APinchtypea.getproperties ()) - { + if(AP. Name = = sp. Name)//determine if property names are the same - { +Ap. SetValue (A, sp.) GetValue (b,NULL),NULL);//gets the value of the B object property copied to the property of the A object A } at } - } - } - Catch(Exception ex) - { - Throwex; in } - returnA; to}Create a copy b
1 /// <summary>2 ///Object A of type A, object B of type B, assigns values of the same name B and a to a3 /// </summary>4 /// <typeparam name= "A" ></typeparam>5 /// <typeparam name= "B" ></typeparam>6 /// <param name= "a" ></param>7 /// <param name= "B" ></param>8 Public Static voidMapper<a, b> (b b,refa A)9 {Ten Try One { AType TypeB = B.gettype ();//Get Type -Type TypeA =typeof(A); - foreach(PropertyInfo SPinchTypeb.getproperties ())//Get property fields of type the { - foreach(PropertyInfo APinchtypea.getproperties ()) - { - if(AP. Name = = sp. Name)//determine if property names are the same + { -Ap. SetValue (A, sp.) GetValue (b,NULL),NULL);//gets the value of the B object property copied to the property of the A object + } A } at } - } - Catch(Exception ex) - { - Throwex; - } in}incoming a copy b
C # uses reflection to replicate the value of the same property between objects of two classes