c#通过反射完成对象自动映射

在 C# 中,可以使用 AutoMapper 库来完成对象之间的映射,而不必手动编写显式的映射代码。但是,如果你希望通过反射来动态完成对象的映射,你可以编写自己的映射逻辑并使用反射来完成这个过程。

下面是一个简单的示例,演示了如何使用反射来完成对象之间的映射:


class Program
{
   
	static void Main()
	{
   
		// 创建源对象
		Person source = new Person {
    Name = "Alice", Age = 25 };

		// 创建目标对象
		PersonDto destination = new PersonDto();
		destination = source.MapTo<Person, PersonDto>();
		// 输出目标对象的属性值
		Console.WriteLine($"Name: {
     destination.Name}, Age: {
     destination.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()
	{
   
		// 创建目标对象
		TDest destination = new TDest();

		// 获取源对象的所有属性
		PropertyInfo[] sourceProperties = typeof(TSource).GetProperties();
		// 获取目标对象的所有属性
		PropertyInfo[] destinationProperties = typeof(TDest).GetProperties();

		// 使用反射完成对象的映射
		foreach (var sourceProperty in sourceProperties)
		{
   
			foreach (var destinationProperty in destinationProperties)
			{
   
				if (sourceProperty.Name == destinationProperty.Name && sourceProperty.PropertyType == destinationProperty.PropertyType)
				{
   
					// 通过反射获取源对象的属性值
					object value = sourceProperty.GetValue(source);
					// 通过反射设置目标对象的属性值
					destinationProperty.SetValue(destination, value);
					break;
				}
			}
		}
		return destination;
	}
}

相关推荐

  1. c#通过反射完成对象自动映射

    2024-02-10 15:34:01       45 阅读
  2. c#通过ExpressionTree 表达式树实现对象关系映射

    2024-02-10 15:34:01       41 阅读
  3. c# datatable 通过反射转成泛型list

    2024-02-10 15:34:01       59 阅读
  4. C#如何通过反射获取外部dll的函数

    2024-02-10 15:34:01       30 阅读
  5. C++类和对象3(未完成

    2024-02-10 15:34:01       32 阅读
  6. C# 反射

    2024-02-10 15:34:01       37 阅读
  7. C# 反射

    2024-02-10 15:34:01       27 阅读
  8. C# 反射

    2024-02-10 15:34:01       22 阅读
  9. <span style='color:red;'>C</span>#-<span style='color:red;'>反射</span>

    C#-反射

    2024-02-10 15:34:01      17 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-10 15:34:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-10 15:34:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-10 15:34:01       82 阅读
  4. Python语言-面向对象

    2024-02-10 15:34:01       91 阅读

热门阅读

  1. 2.8作业

    2024-02-10 15:34:01       46 阅读
  2. 11.3 OpenGL可编程顶点处理:几何着色器

    2024-02-10 15:34:01       52 阅读
  3. 前端代码整洁规范之道

    2024-02-10 15:34:01       47 阅读
  4. C语言scanf()函数的返回值是什么?

    2024-02-10 15:34:01       49 阅读
  5. 【无标题】

    2024-02-10 15:34:01       49 阅读
  6. Python Pickle库原理及使用详解

    2024-02-10 15:34:01       47 阅读
  7. 【C语言】数组

    2024-02-10 15:34:01       45 阅读
  8. Day44 198打家劫舍 213打家劫舍II 337打家劫舍III

    2024-02-10 15:34:01       51 阅读
  9. 刘润--进化的力量--流量新生态

    2024-02-10 15:34:01       48 阅读