用lambda表達式樹替代反射

来源:https://www.cnblogs.com/fode/archive/2018/12/07/10079630.html
-Advertisement-
Play Games

本節重點不講反射機制,而是講lambda表達式樹來替代反射中常用的獲取屬性和方法,來達到相同的效果但卻比反射高效。 每個人都知道,用反射調用一個方法或者對屬性執行SetValue和GetValue操作的時候都會比直接調用慢很多,這其中設計到CLR中內部的處理,不做深究。然而,我們在某些情況下又無法不 ...


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

每個人都知道,用反射調用一個方法或者對屬性執行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; }

 

  對於這種情況,其執行效率是特別低下的,具體多慢在下麵例子會在.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;

            //創建了屬性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; }
        }

 

 以下代碼可能很難看得懂,但只要知道我們創建了屬性的Get、Set這兩個方法就行,其結果最後也能輸出狗的名字 WLJ,擁有ExpressionTree的好處是他有一個名為Compile()的方法,它創建一個代表表達式的代碼塊。現在是最有趣的部分,假設你在編譯時不知道類型(在這篇文章中包含的代碼我在不同的程式集上創建了一個類型)你仍然可以應用這種技術,我將對於常用的屬性的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 = property.GetValue(dog) as String;
            Console.WriteLine(result2);        

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

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

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

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

            //下麵該方法個執行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環境下運行結果如下:

.Net Core環境下運行結果:

 

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

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

代碼下載


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、搭建項目 1、創建一個ASP.NET Core MVC 項目 2、nuget 下載和安裝 MicroSoft.AspNetCore.SignalR vs提示版本衝突 這時我們選擇低版本即可 二、SignalR配置 1、在model中創建一個類MyHub 代碼如下 public class MyH ...
  • delegate void del(); class MyClass1 { public event del eventcount;//創建事件併發布 public void Count() { for (int i = 0; i < 100; i++) { ... ...
  • public class NullToEmptyStringResolver : DefaultContractResolver { /// /// 創建屬性 /// /// 類型 /// 序列化成員 /// protected override IList Creat... ...
  • 這是我定義的實體類 對應的資料庫表 映射文件 數據訪問層寫的是插入語句 錯誤: 捕捉到 NHibernate.Exceptions.GenericADOException HResult=-2146232832 Message=could not insert: [DaYou.Yun.Entity. ...
  • 由於本人是Java入門的開發,在C#開發中遇到的問題,在此記錄一下: 1、client端的send方法不管發送出去沒發送出去,總是顯示發送出去。 查資料得知,send方法是將數據發送到緩存區,並不是直接發送到server。 2、connected 方法,總是顯示已連接上。 一直以為connected ...
  • 在測試中經常會遇到請求一些https的url,但又沒有本地證書,這時候可以用下麵的方法忽略警告 ...
  • 這段時間因公司業務需要.net開發且需要用到DevExpress控制項,我自己研究學習了一下,用的是visual studio(2013)和DevExpress(V14.1.4),VS2013的下載安裝就不說,直接進入正題。 DevExpress(V14.1.4)安裝、破解和漢化的程式下載鏈接 鏈接: ...
  • 在 Asp.Net Core 中,我們常常使用 System.Threading.Timer 這個定時器去做一些需要長期在後臺運行的任務,但是這個定時器在某些場合卻不太靈光,而且常常無法控制啟動和停止,我們需要一個穩定的,類似 WebHost 這樣主機級別的任務管理程式,但是又要比 WebHost ... ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...