In C#, you can use the AutoMapper library to complete mapping between objects without having to manually write explicit mapping code. However, if you want to dynamically complete the mapping of objects through reflection, you can write your own mapping logic and use reflection to complete the process.
During the programming process, we often need to convert one object into another (usually called object mapping).
For example, we have 2 categories:
//Class 1 CLS1class CLS1 { public int i {get; set;} public string str {get; set;} } //Class 2 CLS2class CLS2 { public int i {get; set;} public string str {get; set;} }
Both classes have attributesi
andstr
。
When we need to convert the instance object of CLS1 into an instance object of CLS2, we will normally operate like this:
CLS1 obj1 = new CLS1(){i = 1, str = "ss"}; CLS2 obj2 = new CLS2(); //Map obj1 to obj2 = ; // = 1; = ; // = "ss";
If there are too many attributes, it will be very cumbersome to write. I hope it can be automatically solved by a method, such as this:
//Map the object of CLS1 to the object of CLS2obj2 = Mapper.T1MapToT2<CLS1, CLS2>(obj1); // = 1; = "ss";
Here is a simple example that demonstrates how to use reflection to complete mapping between objects:
class Program { static void Main() { // Create source object Person source = new Person { Name = "Alice", Age = 25 }; // Create target object PersonDto destination = new PersonDto(); destination = <Person, PersonDto>(); // Output the attribute value of the target object ($"Name: {}, Age: {}"); } } class Person { public string Name { get; set; } public int Age { get; set; } } class PersonDto { public string Name { get; set; } public int Age { get; set; } } static class AutoMapper { public static TDest MapTo<TSource, TDest>(this TSource source) where TSource : class, new() where TDest : class, new() { // Create target object TDest destination = new TDest(); // Get all properties of the source object PropertyInfo[] sourceProperties = typeof(TSource).GetProperties(); // Get all properties of the target object PropertyInfo[] destinationProperties = typeof(TDest).GetProperties(); // Use reflection to complete the mapping of objects foreach (var sourceProperty in sourceProperties) { foreach (var destinationProperty in destinationProperties) { if ( == && == ) { // Get the property value of the source object through reflection object value = (source); // Set the property value of the target object through reflection (destination, value); break; } } } return destination; } }
This is the article about the implementation of automatic object mapping through reflection in c#. For more related contents of automatic object mapping of c#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!