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# 对象映射的高性能方案的文章就介绍到这了,更多相关高性能对象映射内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
黄山市民网:https://www.huangshanshimin.com/