C# 高效能物件對映

烏龜會哲_Program發表於2020-12-12

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

 

相關文章