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 ? "平台" : "机构";
}
现在我们来使用两行代码来搞定对象映射问题
为了实现c#教程操作更方便,多对象映射
实现对象映射功能的代码如下:
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;
}
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# 对象映射的高性能方案的文章就介绍到这了,更多相关高性能对象映射内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持