Occasionally when doing a project B Class assigned to A class , Happen A and B Type many of the property field names are the same , Or just the case , It's possible to take advantage of generics , Reflection to write an automatic assignment method .

The following method does not consider the case difference , If you want to consider , You can use the string method ToUpper() 、ToLower() after , Compare the field names to see if they are the same .

 public class MapperModel
{
/// <summary>
/// B Object to assign the same property to A object ,
/// </summary>
/// <typeparam name="A"> type A</typeparam>
/// <typeparam name="B"> type B</typeparam>
/// <param name="b">B object </param>
/// <returns> Return to the new A object </returns>
public static A Mapper<A, B>(B b)
{
A a = Activator.CreateInstance<A>();
try
{
Type Typeb = b.GetType();// Acquisition type
Type Typea = typeof(A);
foreach (PropertyInfo bp in Typeb.GetProperties())// Get property field of type
{
foreach (PropertyInfo ap in Typea.GetProperties())
{
if (ap.Name == bp.Name)// Determine whether the attribute names are the same
{
if (ap.GetSetMethod()!= null)
{
if (bp.GetGetMethod()!=null)
{
ap.SetValue(a, bp.GetValue(b, null), null);// get b The value of the object property is copied to a Object properties }
} }
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return a;
}
}

What should be noted , Do attributes have Get perhaps Set Method ?B attribute Set The accessor is not public or does not exist An exception will occur when assigning values . Empathy :A Property if Get The accessor is not public or does not exist , Exception occurs when taking value

So it uses GetSetMethod(),GetGetMethod() Do judgment . If Get 、Set The accessor cannot get , Then return to null.

I feel that the following code is more readable : Omitting a loop

 /// <summary>
/// Afferent type B The object of b, take b And a A value of the same name is assigned to the created a in
/// </summary>
/// <typeparam name="A"> type A</typeparam>
/// <typeparam name="B"> type B</typeparam>
/// <param name="b"> The type is B Parameters of b</param>
/// <returns> Copy b The value of the same property in a</returns>
public static A MapperTwo<A, B>(B b)
{
A a = Activator.CreateInstance<A>();
try
{
Type Typeb = typeof(B);// Acquisition type
Type Typea = typeof(A);
foreach (PropertyInfo ap in Typea.GetProperties())
{
System.Reflection.PropertyInfo bp = Typeb.GetProperty(ap.Name); // Gets the property with the specified name
if (bp != null) // If B Objects also have this property
{
if (ap.GetSetMethod() != null) // Judge A Whether the object can be used Set Method
{
if (bp.GetGetMethod() != null) // Judge B Whether the object can be used Get Method
{
ap.SetValue(a, bp.GetValue(b, null), null);// get b The value of the object property is copied to a Object properties
}
}
} }
}
catch (Exception ex)
{
throw ex;
}
return a;
}

It is estimated that what I wrote is the following principle , serialize , Deserialization , Case insensitive . Of course , We can't deny the above .

public static A MapperTwo<A, B>(B b)
{
return Newtonsoft.Json.JsonConvert.DeserializeObject<A>(Newtonsoft.Json.JsonConvert.SerializeObject(b));
}

C# Class assignment of the same property

  1. 31 Assign values to the properties of a class by reflection and Object Assignment (clone)

    1. Configuration class package com.da.tool.util.configuration.reflect; /** */ public class JobInfo { private String j ...

  2. 107-PHP Class member property assignment

    <?php class mao{ // Define cats public $age; // Define multiple member properties protected $weight; private $color; } $mao1=new ma ...

  3. 110-PHP Class member property assignment

    <?php class mao{ // Define cats public $age=0; // Define multiple properties and initialize public $weight=50; public $color='white'; } $ ...

  4. iOS Traversal of development Model Class and improve the use of Runtime to Model Class assignment

    In the last blog <iOS The use of development Runtime to Model Class assignment > This paper introduces how to use the runtime to add the method of assigning values to the properties of the entity class in the base class of the entity class , The premise of this method is the dictionary Key Must be the same as the entity class Property ...

  5. I wrote it RunTime One of the functions , Assign values to a property of a class and exchange methods

      1, Assign values to properties #import <UIKit/UIKit.h> @interface UIViewController (RunTime) - (BOOL)setPropertyVal ...

  6. Android Using reflection mechanism to assign values to entity class attributes

    Doing it android Project time , Sometimes I get it from the Internet json Type data , Assign values to entity classes , Entity class attributes can be assigned one by one , If an entity class has many properties , Assignment may take a long time , fortunately Java Provides us with a reflex mechanism . below ...

  7. How to determine whether all the fields in the entity class are null

    1, Assignment between the same attributes of entity class /// <summary> /// Put entity 2 The value of is dynamically assigned to the entity 1( Property with the same name ) /// </summary> /// <param ...

  8. java object-oriented ( Nine ): Class structure : Constructors ( One ) brief introduction ; Property assignment order ;JavaBean The concept of

    1. Constructors ( Or construction method ):Constructor The role of the constructor : * 1. Create objects * 2. Information about the initialization object 2. Instructions : * 1. If there is no explicit definition of class constructor , By default, the system provides an empty parameter constructor * 2 ...

  9. IL Interface and class properties

    I learned from the last article IL To get started , Next, let's learn about the properties of the following class through two examples . The use of constructors and interfaces One . Attributes of a class . Constructors 1. Let's take a look at the class we're going to build C# Code , And then we can move on IL The implementation of the , The sample code is as follows : [Ser ...

Random recommendation

  1. How to do well GPS Platform hardware and software integration test

    Integration testing is to build a larger system or platform , Several parts of the system are usually developed by different teams or even different companies , In the past, when doing information software development , The integration test is usually the integration test between different software subsystems , They are often confused by this stage of testing ...

  2. Unrecognized configuration section system.serviceModel

    It's also the answer from the Internet , It really solved the problem I don't know if it's the reason for the patch update , The program that was run before , All of a sudden, I can't , In limine , The operation immediately flashed back , In the event viewer , I don't see any specific error messages , Fortunately cmd The program , therefore , ...

  3. Angularjs Achieve the effect of online evaluation of mobile terminal

    notes : In this paper angular Version is 1.6 One . Run the renderings Two . demand 1. When you click on an option , The background turns yellow ( That is, the selected state ), And automatically switch to the next question 2. Switch to the next question , The top schedule changes 3. When selecting the corresponding ...

  4. 《java Season one 》 Two dimensional array three cases explain in detail

    Case a : Traversing a two-dimensional array /* demand : Two dimensional array traversal The outer loop controls the length of the two-dimensional array , In fact, it is the number of rows of one-dimensional array . The inner loop controls the length of the one-dimensional array , Every line , The number of elements in a one-dimensional array . */ class Array ...

  5. In depth understanding of pthread_cond_wait、pthread_cond_signal

    ===============================man pthread_cond_wait The explanation of ========================== LINUX Multithreading programming environment will certainly encounter ...

  6. MongoDB The significance of key indicators &amp; The interval meaning of each value &amp; Deploy

    ## part 1 mms chart What's MMS MongoDB Management Service (MMS) is a suite of services for managing Mongo ...

  7. golang xorm Use of framework

    1. establish engine engine, err := xorm.NewEngine(driverName, dataSourceName) The above code creates a database engine , You can create multiple... In one program engi ...

  8. Oracle Simple backup and recovery - Export and import (2)

    ylbtech-Oracle:Oracle Simple backup and recovery - Export and import (2) Simple backup and recovery - Export and import (2) 1. The user imports and exports a table in the file (emp) Return to the top 0.1, We are sql plus in ...

  9. When Ruby Of model When the name goes wrong , In reality view Display error prompt when

    app/controllers/courses_controller.rb:1:in `<top (required)>' app/controllers/courses_controll ...

  10. Windows Phone 8 Get device name

    By using Microsoft.Phone.Info.DeviceStatus class , We can get some information about the device , Such as equipment manufacturers , Equipment name, etc . adopt Microsoft.Phone.Info.DeviceStatus ...