日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

delegate、Lambda表达式、Func委托和Expression(TDelegate)表达式目录树

發布時間:2025/7/14 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 delegate、Lambda表达式、Func委托和Expression(TDelegate)表达式目录树 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

1.delegate

MSDN:一種安全地封裝方法的類型,它與 C 和 C++ 中的函數指針類似。與 C 中的函數指針不同,委托是面向對象的、類型安全的和保險的。委托的類型由委托的名稱定義

class Program{const int num = 100;delegate bool delCompare(int a);static void Main(string[] args){delCompare hander = DelegateMethod;hander(1);}public static bool DelegateMethod(int a){return a > num;}}

用IL Disassemble查看


匿名委托:

匿名委托即使用了匿名方法的委托,IL層中的代碼中會為匿名函數生一個靜態的函數,本次的代碼中的函數名是:CS$<>9__CachedAnonymousMethodDelegate1

class Program{const int num = 100;delegate bool delCompare(int a);static void Main(string[] args){delCompare del = delegate(int a) { return a > num; };}}

用IL Disassemble查看

Lambda表達式

使用Lambda表達式與上一個Demo中使用匿名函數生成的IL代碼是完全一樣的

class Program{const int num = 100;delegate bool delCompare(int a);static void Main(string[] args){delCompare del = a => a > num;}}

Func<T1..TResult>

使用Func<T1…TResult>中的Demo中,在IL層代中有所不同。代碼中沒有用到delegate,相當于在Main方法中直接調用了一個靜態方法。理論上Func<T1…TResult>比delegate在時間和空間的效率都要高

class Program{const int num = 100;//delegate bool delCompare(int a);static void Main(string[] args){Func<int, bool> del = a => a > num;}

?

}

Expression(TDelegate)

表達式目錄樹以數據形式表示語言級別代碼。數據存儲在樹形結構中。表達式目錄樹中的每個節點都表示一個表達式。以下Demo中IL層的代碼中并未生成任何靜態函數。

class Program{const int num = 100;//delegate bool delCompare(int a);static void Main(string[] args){Expression<Func<int, bool>> exp = a => a > num; //生在表達式Func<int,bool> fun = exp.Compile(); //編輯表達式fun(1); //執行表達式}}

查看Main函數,在IL層代碼中會對Expression動太編譯生成實例!0,再通過Invoke(!0)調用方法

IL_0045: callvirt instance !0 class [System.Core]System.Linq.Expressions.Expression`1<class [mscorlib]System.Func`2<int32,bool>>::Compile()
IL_004a: stloc.1
IL_004b: ldloc.1
IL_004c: ldc.i4.1
IL_004d: callvirt instance !1 class [mscorlib]System.Func`2<int32,bool>::Invoke(!0)
IL_0052: pop
IL_0053: ret

總結:

匿名delegate和Lambda表達式本質是一樣的,Func<T1..TResult>委托與delegate不同,它沒有委托的異常調用等特性,在IL層生成的代碼不同,執行方式不同。Expression(TDelegate)則是語言級別的,用于動太生成表達式,理論上Expression(TDelegate)效率最差。但在Linq表達式中必須用到

轉載于:https://www.cnblogs.com/yexinw/archive/2012/08/08/2628655.html

總結

以上是生活随笔為你收集整理的delegate、Lambda表达式、Func委托和Expression(TDelegate)表达式目录树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。