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;
	}
}
相关推荐
雨落倾城夏未凉3 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫4 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫5 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6255 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902115 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠5 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫7 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech8 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf9 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6259 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#