当前位置: 首页 > news >正文

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;}
}
http://www.lryc.cn/news/298218.html

相关文章:

  • ef core原始sql查询
  • 2024 CKS 题库 | 4、RBAC - RoleBinding
  • Docker Compose实例
  • Mac上新版InfluxDB使用教程
  • 性能篇:网络通信优化之序列化
  • 【UE 游戏编程基础知识】
  • 原语,原子,线程安全
  • fast.ai 机器学习笔记(一)
  • Linux下的socket操作
  • 爬虫练习——动态网页的爬取(股票和百度翻译)
  • Name or service not known问题解决和分析过程解析
  • emmet语法
  • 【PTA主观题】8-1 文件操作
  • 机器学习算法决策树
  • ssh和sftp服务分离
  • Bootstrap学习三
  • 第77讲用户管理功能实现
  • 锐捷(十九)锐捷设备的接入安全
  • 【MySQL题】——基础概念论述(二)
  • Spring Boot + flowable 快速实现工作流
  • (已解决)LaTeX Error: File `svproc.cls‘ not found. (用Springer LNCS 会议Proceedings模板)
  • Spring Boot 自定义指标
  • 安全的接口访问策略
  • 最佳视频转换器软件:2024年视频格式转换的选择
  • 深入理解 Nginx 插件及功能优化指南
  • 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之Blank组件
  • InternLM大模型实战-4.XTuner大模型低成本微调实战
  • 【SpringBoot篇】解决Redis分布式锁的 误删问题 和 原子性问题
  • 蓝桥杯Web应用开发-CSS3 新特性【练习三:文本阴影】
  • LRU缓存