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

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

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

csharp 复制代码
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;
	}
}
相关推荐
Chen—LSN2 小时前
C语言——深度理解指针(6)
c语言·开发语言·算法·c#
在世修行14 小时前
从零打造 C# 工业视觉检测系统(八):Modbus RTU 协议解析与 PLC 剔除控制实战
开发语言·c#
花落人散处18 小时前
CDiskClean 开发历程——忽略进程_拖拽功能实现参考
c#
xcLeigh19 小时前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
花落人散处20 小时前
CDiskClean 开发历程——文件&进程实时监控-实现方案参考
c#
猿长大人1 天前
C# | MediatR 入门指南:后端架构解耦
分布式·后端·架构·c#·.net
回忆2012初秋1 天前
C# 中的 EAP:基于事件的异步编程全面指南(一)
开发语言·c#
曹牧1 天前
C#:Type
开发语言·c#
用户3721574261351 天前
C# 如何在 Excel 中创建下拉列表:3 种常见数据源实现方式
c#
czhc11400756631 天前
工业视觉检测中的通用设计模式与技术笔记
c#