欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# 快速高效率復(fù)制對象(表達(dá)式樹)

 更新時(shí)間:2017年04月06日 09:01:24   作者:Emrys5  
在代碼中經(jīng)常會遇到需要把對象復(fù)制一遍,或者把屬性名相同的值復(fù)制一遍。本文將對其解決方法進(jìn)行詳細(xì)介紹。下面跟著小編一起來看下吧

1、需求

在代碼中經(jīng)常會遇到需要把對象復(fù)制一遍,或者把屬性名相同的值復(fù)制一遍。

比如:

public class Student
 {
  public int Id { get; set; }
  public string Name { get; set; } 
  public int Age { get; set; } 
 }

 public class StudentSecond
 {
  public int Id { get; set; }
  public string Name { get; set; }
  public int Age { get; set; } 
 }

Student s = new Student() { Age = 20, Id = 1, Name = "Emrys" };

我們需要給新的Student賦值

Student ss = new Student { Age = s.Age, Id = s.Id, Name = s.Name };

再或者給另一個(gè)類StudentSecond的屬性賦值,兩個(gè)類屬性的名稱和類型一致。

StudentSecond ss = new StudentSecond { Age = s.Age, Id = s.Id, Name = s.Name };

2、解決辦法

當(dāng)然最原始的辦法就是把需要賦值的屬性全部手動手寫。這樣的效率是最高的。但是這樣代碼的重復(fù)率太高,而且代碼看起來也不美觀,更重要的是浪費(fèi)時(shí)間,如果一個(gè)類有幾十個(gè)屬性,那一個(gè)一個(gè)屬性賦值豈不是浪費(fèi)精力,像這樣重復(fù)的勞動工作更應(yīng)該是需要優(yōu)化的。

2.1、反射

反射應(yīng)該是很多人用過的方法,就是封裝一個(gè)類,反射獲取屬性和設(shè)置屬性的值。

private static TOut TransReflection<TIn, TOut>(TIn tIn)
  {
   TOut tOut = Activator.CreateInstance<TOut>();
   foreach (var itemOut in tOut.GetType().GetProperties())
   {
    var itemIn = tIn.GetType().GetProperties().Where(i => i.Name == itemOut.Name).FirstOrDefault();
    if (itemIn != null)
    {
     itemOut.SetValue(tOut, itemIn.GetValue(tIn));
    }
   }
   return tOut;
  }

調(diào)用:StudentSecond ss= TransReflection<Student, StudentSecond>(s);

調(diào)用一百萬次耗時(shí):2464毫秒

2.2、序列化

序列化的方式有很多種,有二進(jìn)制、xml、json等等,今天我們就用Newtonsoft的json進(jìn)行測試。

調(diào)用:

StudentSecond ss= JsonConvert.DeserializeObject<StudentSecond>(JsonConvert.SerializeObject(s));

調(diào)用一百萬次耗時(shí):2984毫秒

從這可以看出序列化和反射效率差別不大。

3、表達(dá)式樹

3.1、簡介

關(guān)于表達(dá)式樹不了解的可以百度。

也就是說復(fù)制對象也可以用表達(dá)式樹的方式。

  Expression<Func<Student, StudentSecond>> ss = (x) => new StudentSecond { Age = x.Age, Id = x.Id, Name = x.Name };
  var f = ss.Compile();
  StudentSecond studentSecond = f(s);

這樣的方式我們可以達(dá)到同樣的效果。

有人說這樣的寫法和最原始的復(fù)制沒有什么區(qū)別,代碼反而變多了呢,這個(gè)只是第一步。

3.2、分析代碼

我們用ILSpy反編譯下這段表達(dá)式代碼如下:

ParameterExpression parameterExpression;
 Expression<Func<Student, StudentSecond>> ss = Expression.Lambda<Func<Student, StudentSecond>>(Expression.MemberInit(Expression.New(typeof(StudentSecond)), new MemberBinding[]
 {
  Expression.Bind(methodof(StudentSecond.set_Age(int)), Expression.Property(parameterExpression, methodof(Student.get_Age()))),
  Expression.Bind(methodof(StudentSecond.set_Id(int)), Expression.Property(parameterExpression, methodof(Student.get_Id()))),
  Expression.Bind(methodof(StudentSecond.set_Name(string)), Expression.Property(parameterExpression, methodof(Student.get_Name())))
 }), new ParameterExpression[]
 {
  parameterExpression
 });
 Func<Student, StudentSecond> f = ss.Compile();
 StudentSecond studentSecond = f(s);

那么也就是說我們只要用反射循環(huán)所有的屬性然后Expression.Bind所有的屬性。最后調(diào)用Compile()(s)就可以獲取正確的StudentSecond。

看到這有的人又要問了,如果用反射的話那豈不是效率很低,和直接用反射或者用序列化沒什么區(qū)別嗎?

當(dāng)然這個(gè)可以解決的,就是我們的表達(dá)式樹可以緩存。只是第一次用的時(shí)候需要反射,以后再用就不需要反射了。

3.3、復(fù)制對象通用代碼

為了通用性所以其中的Student和StudentSecond分別泛型替換。

private static Dictionary<string, object> _Dic = new Dictionary<string, object>();

  private static TOut TransExp<TIn, TOut>(TIn tIn)
  {
   string key = string.Format("trans_exp_{0}_{1}", typeof(TIn).FullName, typeof(TOut).FullName);
   if (!_Dic.ContainsKey(key))
   {
    ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
    List<MemberBinding> memberBindingList = new List<MemberBinding>();

    foreach (var item in typeof(TOut).GetProperties())
    {
     MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
     MemberBinding memberBinding = Expression.Bind(item, property);
     memberBindingList.Add(memberBinding);
    }

    MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
    Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
    Func<TIn, TOut> func = lambda.Compile();
    _Dic[key] = func;
   }
   return ((Func<TIn, TOut>)_Dic[key])(tIn);
  }

調(diào)用:StudentSecond ss= TransExp<Student, StudentSecond>(s);

調(diào)用一百萬次耗時(shí):564毫秒

4、總結(jié)

從以上的測試和分析可以很容易得出,用表達(dá)式樹是可以達(dá)到效率與書寫方式二者兼?zhèn)涞姆椒ㄖ?,總之比傳統(tǒng)的序列化和反射更加優(yōu)秀。

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • winform樹形菜單無限級分類實(shí)例

    winform樹形菜單無限級分類實(shí)例

    本文介紹了“winform樹形菜單無限級分類實(shí)例”,需要的朋友可以參考一下
    2013-03-03
  • .Net6開發(fā)winform程序使用依賴注入

    .Net6開發(fā)winform程序使用依賴注入

    本文詳細(xì)講解了.Net6開發(fā)winform程序使用依賴注入的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • C#轉(zhuǎn)換日期類型實(shí)例

    C#轉(zhuǎn)換日期類型實(shí)例

    這篇文章主要介紹了C#轉(zhuǎn)換日期類型的方法,以實(shí)例形式分析了將日期格式轉(zhuǎn)換為Unix時(shí)間戳與時(shí)區(qū)結(jié)合的形式,是比較實(shí)用的技巧,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2014-12-12
  • C#異步編程詳解

    C#異步編程詳解

    本文主要介紹異步編程中Task、Async和Await的基礎(chǔ)知識。具有很好的參考價(jià)值,下面跟著小編一起來看下吧
    2017-02-02
  • MessageBox的Buttons和三級聯(lián)動效果

    MessageBox的Buttons和三級聯(lián)動效果

    這篇文章主要介紹了MessageBox的Buttons和三級聯(lián)動的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-11-11
  • HashTable、HashSet和Dictionary的區(qū)別點(diǎn)總結(jié)

    HashTable、HashSet和Dictionary的區(qū)別點(diǎn)總結(jié)

    在本篇文章里小編給大家整理的是關(guān)于HashTable、HashSet和Dictionary的區(qū)別點(diǎn),需要的朋友們可以學(xué)習(xí)下。
    2020-03-03
  • WinForm遍歷窗體所有子控件的方法

    WinForm遍歷窗體所有子控件的方法

    這篇文章主要介紹了WinForm遍歷窗體所有子控件的方法,涉及C#遞歸遍歷相關(guān)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2016-07-07
  • Unity實(shí)現(xiàn)UI光暈效果(發(fā)光效果)

    Unity實(shí)現(xiàn)UI光暈效果(發(fā)光效果)

    這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)UI光暈效果,發(fā)光效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-01-01
  • C#如何將DLL打包到程序中

    C#如何將DLL打包到程序中

    這篇文章主要介紹了C#如何將DLL打包到程序中問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • C#實(shí)現(xiàn)簡單的計(jì)算器功能

    C#實(shí)現(xiàn)簡單的計(jì)算器功能

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)簡單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-01-01

最新評論