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