C# 对象映射的高性能方案
程序员文章站
2022-04-11 09:49:23
1.之前在使用automapper 框架感觉用着比较不够灵活,而且主要通过表达式树api 实现对象映射 ,写着比较讨厌,当出现复杂类型和嵌套类型时性能直线下降,甚至不如序列化快。2.针对automap...
1.之前在使用automapper 框架感觉用着比较不够灵活,而且主要通过表达式树api 实现对象映射 ,写着比较讨厌,当出现复杂类型和嵌套类型时性能直线下降,甚至不如序列化快。
2.针对automapper 处理复杂类型和嵌套类型时性能非常差的情况,自己实现一个简化版对象映射的高性能方案
public class article { public int id { get; set; } public string categoryid { get; set; } public string title { get; set; } public string pic { get; set; } public string host { get; set; } public string pichost => pic.formathosturl(host); public string content { get; set; } public bool topstatus { get; set; } public datetime publishdate { get; set; } public string lastupdateuser { get; set; } public datetime lastupdatedate { get; set; } public bool isteacher { get; set; } public bool isparent { get; set; } public bool isorg { get; set; } public bool isleaner { get; set; } public string touserstr { get { list<string> strarr = new list<string>(); if (isleaner) { strarr.add("学员"); } if (isorg) { strarr.add("机构"); } if (isparent) { strarr.add("家长"); } if (isteacher) { strarr.add("老师"); } return string.join(",", strarr); } } public int orgid { get; set; } public object orginfo { get; set; } public string isplatformstr => orgid == 0 ? "平台" : "机构"; }
现在我们来使用两行代码来搞定对象映射问题
为了实现操作更方便,多对象映射
实现对象映射功能的代码如下:
public static t copyobjvalue<t>(this t toobj, object fromobj) where t : class { if (fromobj != null && toobj != null) { var otherobjporps = fromobj.gettype().getproperties(); foreach (var formp in otherobjporps) { var top = toobj.gettype().getproperty(formp.name); if (top != null) { try { top.setvalue(toobj, formp.getvalue(fromobj)); } catch (exception e) { console.writeline(e.message); } } } } return toobj; }
到此这篇关于c# 对象映射的高性能方案的文章就介绍到这了,更多相关高性能对象映射内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Spring中创建Bean对象的方式
推荐阅读
-
【MyBatis】---- 引入映射器mapper文件失败的解决方案
-
【转载】C#的Merge方法合并两个DataTable对象的数据
-
MyBatis 不封装对象获取数据库值的解决方案
-
c# List find()方法返回值的问题说明(返回结果为对象的指针)
-
C#中的DataSet、string、DataTable、对象转换成Json的实现代码
-
C#中的多线程超时处理实践方案
-
ajaxFileUpload插件,C#返回Json数据报错问题的解决方案
-
浅析C#中数组,ArrayList与List对象的区别
-
C#中Monitor对象与Lock关键字的区别分析
-
c#创建Graphics对象的三种方法