最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

利用lambda表達式樹優(yōu)化反射詳解

 更新時間:2018年12月07日 09:52:26   作者:Fode  
這篇文章主要給大家介紹了關于如何利用lambda表達式樹優(yōu)化反射的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

本節(jié)重點不講反射機制,而是講lambda表達式樹來替代反射中常用的獲取屬性和方法,來達到相同的效果但卻比反射高效。

每個人都知道,用反射調用一個方法或者對屬性執(zhí)行SetValue和GetValue操作的時候都會比直接調用慢很多,這其中設計到CLR中內部的處理,不做深究。然而,我們在某些情況下又無法不使用反射,比如:在一個ORM框架中,你要將一個DataRow轉化為一個對象,但你又不清楚該對象有什么屬性,這時候你就需要寫一個通用的泛型方法來處理,以下代碼寫得有點惡心,但不妨礙理解意思:

//將DataReader轉化為一個對象
     private static T GetObj<T>(SqliteDataReader reader) where T : class
 {
  T obj = new T();
  PropertyInfo[] pros = obj.GetType().GetProperties();
  foreach (PropertyInfo item in pros)
  {
  try
  {
   Int32 Index = reader.GetOrdinal(item.Name);
   String result = reader.GetString(Index);
   if (typeof(String) == item.PropertyType)
   {
   item.SetValue(obj, result);
   continue;
   }
   if (typeof(DateTime) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToDateTime(result));
   continue;
   }
   if (typeof(Boolean) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToBoolean(result));
   continue;
   }
   if (typeof(Int32) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToInt32(result));
   continue;
   }
   if (typeof(Single) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToSingle(result));
   continue;
   }
   if (typeof(Single) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToSingle(result));
   continue;
   }
   if (typeof(Double) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToDouble(result));
   continue;
   }
   if (typeof(Decimal) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToDecimal(result));
   continue;
   }
   if (typeof(Byte) == item.PropertyType)
   {
   item.SetValue(obj, Convert.ToByte(result));
   continue;
   }
  }
  catch (ArgumentOutOfRangeException ex)
  {
   continue;
  }
  }
  return obj;
 }

對于這種情況,其執(zhí)行效率是特別低下的,具體多慢在下面例子會在.Net Core平臺上和.Net Framework4.0運行測試案例.對于以上我舉例的情況,效率上我們還可以得到提升。但對于想在運行時修改一下屬性的名稱或其他操作,反射還是一項特別的神器,因此在某些情況下反射還是無法避免的。

但是對于只是簡單的SetValue或者GetValue,包括用反射構造函數,我們可以想一個中繼的方法,那就是使用表達式樹。對于不理解表達式樹的,可以到微軟文檔查看,點擊我。表達式樹很容易通過對象模型表示表達式,因此強烈建議學習。查看以下代碼:

static void Main()
 {
  Dog dog = new Dog();
  PropertyInfo propertyInfo = dog.GetType().GetProperty(nameof(dog.Name)); //獲取對象Dog的屬性
  MethodInfo SetterMethodInfo = propertyInfo.GetSetMethod(); //獲取屬性Name的set方法

  ParameterExpression param = Expression.Parameter(typeof(Dog), "param");
  Expression GetPropertyValueExp = Expression.Lambda(Expression.Property(param, nameof(dog.Name)), param);
  Expression<Func<Dog, String>> GetPropertyValueLambda = (Expression<Func<Dog, String>>)GetPropertyValueExp;
  ParameterExpression paramo = Expression.Parameter(typeof(Dog), "param");
  ParameterExpression parami = Expression.Parameter(typeof(String), "newvalue");
  MethodCallExpression MethodCallSetterOfProperty = Expression.Call(paramo, SetterMethodInfo, parami);
  Expression SetPropertyValueExp = Expression.Lambda(MethodCallSetterOfProperty, paramo, parami);
  Expression<Action<Dog, String>> SetPropertyValueLambda = (Expression<Action<Dog, String>>)SetPropertyValueExp;

  //創(chuàng)建了屬性Name的Get方法表達式和Set方法表達式,當然只是最簡單的
  Func<Dog, String> Getter = GetPropertyValueLambda.Compile(); 
  Action<Dog, String> Setter = SetPropertyValueLambda.Compile();

  Setter?.Invoke(dog, "WLJ"); //我們現在對dog這個對象的Name屬性賦值
  String dogName = Getter?.Invoke(dog); //獲取屬性Name的值
  
  Console.WriteLine(dogName);
  Console.ReadKey();
 }

 public class Dog
 {
  public String Name { get; set; }
 }

以下代碼可能很難看得懂,但只要知道我們創(chuàng)建了屬性的Get、Set這兩個方法就行,其結果最后也能輸出狗的名字 WLJ,擁有ExpressionTree的好處是他有一個名為Compile()的方法,它創(chuàng)建一個代表表達式的代碼塊。現在是最有趣的部分,假設你在編譯時不知道類型(在這篇文章中包含的代碼我在不同的程序集上創(chuàng)建了一個類型)你仍然可以應用這種技術,我將對于常用的屬性的set,get操作進行分裝。

/// <summary>
   /// 屬性類,仿造反射中的PropertyInfo
 /// </summary>
   public class Property
 {

  private readonly PropertyGetter getter;
  private readonly PropertySetter setter;
  public String Name { get; private set; }

  public PropertyInfo Info { get; private set; }

  public Property(PropertyInfo propertyInfo)
  {
   if (propertyInfo == null)
    throw new NullReferenceException("屬性不能為空");
   this.Name = propertyInfo.Name;
   this.Info = propertyInfo;
   if (this.Info.CanRead)
   {
    this.getter = new PropertyGetter(propertyInfo);
   }

   if (this.Info.CanWrite)
   {
    this.setter = new PropertySetter(propertyInfo);
   }
  }


  /// <summary>
     /// 獲取對象的值
  /// </summary>
    /// <param name="instance"></param>
    /// <returns></returns>
     public Object GetValue(Object instance)
  {
   return getter?.Invoke(instance);
  }


  /// <summary>
     /// 賦值操作
  /// </summary>
    /// <param name="instance"></param>
    /// <param name="value"></param>
     public void SetValue(Object instance, Object value)
  {
   this.setter?.Invoke(instance, value);
  }

  private static readonly ConcurrentDictionary<Type, Core.Reflection.Property[]> securityCache = new ConcurrentDictionary<Type, Property[]>();

  public static Core.Reflection.Property[] GetProperties(Type type)
  {
   return securityCache.GetOrAdd(type, t => t.GetProperties().Select(p => new Property(p)).ToArray());
  }

 }

  /// <summary>
   /// 屬性Get操作類
  /// </summary>
    public class PropertyGetter
  {
  private readonly Func<Object, Object> funcGet;

  public PropertyGetter(PropertyInfo propertyInfo) : this(propertyInfo?.DeclaringType, propertyInfo.Name)
  {

  }

  public PropertyGetter(Type declareType, String propertyName)
  {
   if (declareType == null)
   {
    throw new ArgumentNullException(nameof(declareType));
   }
   if (propertyName == null)
   {
    throw new ArgumentNullException(nameof(propertyName));
   }



   this.funcGet = CreateGetValueDeleagte(declareType, propertyName);
  }


  //代碼核心部分
     private static Func<Object, Object> CreateGetValueDeleagte(Type declareType, String propertyName)
  {
   // (object instance) => (object)((declaringType)instance).propertyName

       var param_instance = Expression.Parameter(typeof(Object));
   var body_objToType = Expression.Convert(param_instance, declareType);
   var body_getTypeProperty = Expression.Property(body_objToType, propertyName);
   var body_return = Expression.Convert(body_getTypeProperty, typeof(Object));
   return Expression.Lambda<Func<Object, Object>>(body_return, param_instance).Compile();
  }

  public Object Invoke(Object instance)
  {
   return this.funcGet?.Invoke(instance);
  }
 }


  public class PropertySetter
 {
  private readonly Action<Object, Object> setFunc;

  public PropertySetter(PropertyInfo property) 
  {
   if (property == null)

   {
    throw new ArgumentNullException(nameof(property));
   }
   this.setFunc = CreateSetValueDelagate(property);
  }



  private static Action<Object, Object> CreateSetValueDelagate(PropertyInfo property)
  {
   // (object instance, object value) => 
   //  ((instanceType)instance).Set_XXX((propertyType)value)

   //聲明方法需要的參數
   var param_instance = Expression.Parameter(typeof(Object));
   var param_value = Expression.Parameter(typeof(Object));

   var body_instance = Expression.Convert(param_instance, property.DeclaringType);
   var body_value = Expression.Convert(param_value, property.PropertyType);
   var body_call = Expression.Call(body_instance, property.GetSetMethod(), body_value);

   return Expression.Lambda<Action<Object, Object>>(body_call, param_instance, param_value).Compile();
  }

  public void Invoke(Object instance, Object value)
  {
   this.setFunc?.Invoke(instance, value);
  }
 }

在將代碼應用到實例:

   Dog dog = new Dog();
   PropertyInfo propertyInfo = dog.GetType().GetProperty(nameof(dog.Name));
   
   //反射操作
   propertyInfo.SetValue(dog, "WLJ");
   String result = propertyInfo.GetValue(dog) as String;
   Console.WriteLine(result);
   
   //表達式樹的操作
   Property property = new Property(propertyInfo);
   property.SetValue(dog, "WLJ2");
   String result2 = propertyInfo.GetValue(dog) as String;
   Console.WriteLine(result2);

發(fā)現其實現的目的與反射一致,但效率卻有明顯的提高。

以下測試以下他們兩之間的效率。測試代碼如下:

   Student student = new Student();
   PropertyInfo propertyInfo = student.GetType().GetProperty(nameof(student.Name));
   Property ExpProperty = new Property(propertyInfo);

   Int32 loopCount = 1000000;
   CodeTimer.Initialize(); //測試環(huán)境初始化

   //下面該方法個執(zhí)行1000000次

   CodeTimer.Time("基礎反射", loopCount, () => { 
    propertyInfo.SetValue(student, "Fode",null);
   });
   CodeTimer.Time("lambda表達式樹", loopCount, () => {
    ExpProperty.SetValue(student, "Fode");
   });
   CodeTimer.Time("直接賦值", loopCount, () => {
    student.Name = "Fode";
   });
   Console.ReadKey();

其.Net4.0環(huán)境下運行結果如下:

.Net Core環(huán)境下運行結果:

從以上結果可以知道,迭代同樣的次數反射需要183ms,而用表達式只要34ms,直接賦值需要7ms,在效率上,使用表達式這種方法有顯著的提高,您可以看到使用此技術可以完全避免使用反射時的性能損失。反射之所以效率有點低主要取決于其加載的時候時在運行期下,而表達式則在編譯期,下篇有空將會介紹用Emit技術優(yōu)化反射,會比表達式略快一點。

注:對于常用對象的屬性,最好將其緩存起來,這樣效率會更高。。

代碼下載

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關文章

  • c#如何使用UDP進行聊天通信

    c#如何使用UDP進行聊天通信

    這篇文章主要介紹了c#如何使用UDP進行聊天通信問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • c#實現metro文件壓縮解壓示例

    c#實現metro文件壓縮解壓示例

    這篇文章主要介紹了c#實現metro文件壓縮解壓示例,實現了zip中增加一張新圖片、刪除文件的方法,需要的朋友可以參考下
    2014-03-03
  • C#無損高質量壓縮圖片實現代碼

    C#無損高質量壓縮圖片實現代碼

    這篇文章主要為大家詳細介紹了C#無損高質量壓縮圖片的實現代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • C#中實現向數組中動態(tài)添加元素

    C#中實現向數組中動態(tài)添加元素

    這篇文章主要介紹了C#中實現向數組中動態(tài)添加元素方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Unity3d 如何更改Button的背景色

    Unity3d 如何更改Button的背景色

    這篇文章主要介紹了unity3d GUI.Button 自定義字體大小及透明背景方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • C#微信公眾號開發(fā)之用戶管理

    C#微信公眾號開發(fā)之用戶管理

    這篇文章介紹了C#微信公眾號開發(fā)之用戶管理,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • C#多線程系列之手動線程通知

    C#多線程系列之手動線程通知

    本文詳細講解了C#多線程中的手動線程通知,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-02-02
  • C#獲取所有進程的方法

    C#獲取所有進程的方法

    在本篇文章里小編給大家分享了關于C#獲取所有進程的方法和步驟,有需要的朋友們跟著學習參考下。
    2018-12-12
  • 史上最簡潔C# 生成條形碼圖片思路及示例分享

    史上最簡潔C# 生成條形碼圖片思路及示例分享

    這篇文章主要介紹了史上最簡潔C# 生成條形碼圖片思路及示例分享,需要的朋友可以參考下
    2015-01-01
  • C# BeginInvoke實現異步編程方式

    C# BeginInvoke實現異步編程方式

    這篇文章主要介紹了C# BeginInvoke實現異步編程方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01

最新評論

都安| 乡城县| 剑川县| 巴彦县| 武夷山市| 浦县| 乌什县| 壤塘县| 洮南市| 台山市| 秦安县| 徐闻县| 西城区| 东平县| 沂南县| 崇州市| 遵义县| 喀什市| 霍城县| 铜梁县| 尼玛县| 嘉峪关市| 轮台县| 定西市| 洞头县| 正阳县| 潜山县| 富川| 贡嘎县| 贺州市| 金华市| 广宗县| 资中县| 枣庄市| 台东市| 杂多县| 米脂县| 阜宁县| 岳普湖县| 鲁山县| 马尔康县|