软件编程
位置:首页>> 软件编程>> C#编程>> C# 对象映射的高性能方案

C# 对象映射的高性能方案

作者:乌龟会哲_Program  发布时间:2021-09-22 08:03:19 

标签:C#,对象映射

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# 对象映射的高性能方案

为了实现操作更方便,多对象映射

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;
 }

来源:https://www.cnblogs.com/LeeMicroShake/p/14125166.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com