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;
	}
}
相关推荐
kimloner4 小时前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
阿松爱学习5 小时前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
半亩码田5 小时前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#
FPGA小徐6 小时前
【一生一芯 / PA】异常响应机制:RISC-V 中 ecall → mtvec → mret 的完整代
开发语言·数据库·c#
淡海水6 小时前
02-04-原理篇-GC Roots与对象图遍历
算法·unity·c#·图·gc·遍历·roots
胖纸不争11 小时前
嫌桌面 Agent 太重,我“自己”写了一个
ai·c#·net core
当青春邂逅吉米多维奇15 小时前
C#图解教程(第5版) 同步方法
开发语言·c#
波力海苔夹心脆67515 小时前
C# 机器视觉实战:单相机引导机械手精准贴合,从拍照、偏差计算(平移+旋转)到坐标补偿全解
开发语言·经验分享·数码相机·c#·视觉检测·.net
Behavior17 小时前
国内下载使用 Unity 6000 踩坑点总结
c#·unity3d·游戏开发
czhc114007566318 小时前
一张图从哪来,一个判断往哪走
c#