.NET Framework委托的預定義方法介紹
.NET Framework開發環境對于開發人員來說是一個非常實用的開發平臺。我們可以通過它來進行WEB應用程序的部署。前言:從.NET Framework2.0開始以來,系統預定義的委托使使代碼看起來有點像“天書”,再加上匿名表達式,以及后面Lambda表達式的“摻和”,代碼就更加難懂了,于是自己就一點點查MSDN,到現在終于有點入門了。#t#
用.NET Framework委托:
- 1、public delegate void Action< T>(T obj )
- 2、public delegate TResult Func< TResult>()
- 3、public delegate bool Predicate< T>(T obj)
其中:Action和Func還包括從不帶任何參數到最多四個參數的重載?
1、public delegate void Action< T>(T obj )
封裝一個方法,該方法只采用一個參數并且不返回值。
Code
- Action< string> messageTarget;
- messageTarget = s => Console.
WriteLine(s);- messageTarget("Hello, World!");
2、public delegate TResult Func<TResult>()
封裝一個具有一個參數并返回 TResult 參數指定的類型值的方法。
類型參數T
此委托封裝的方法的參數類型。
TResult
此.NET Framework委托封裝的方法的返回值類型
Code
- public static void Main()
- {
- // Instantiate delegate to reference UppercaseString method
- ConvertMethod convertMeth = UppercaseString;
- string name = "Dakota";
- // Use delegate instance to call UppercaseString method
- Console.WriteLine(convertMeth(name));
- }
- private static string UppercaseString(string inputString)
- {
- return inputString.ToUpper();
- }
3、public delegate bool Predicate<T>(T obj)
表示定義一組條件并確定指定對象是否符合這些條件的方法。
類型參數
T:要比較的對象的類型。
返回值
如果 obj 符合由此委托表示的方法中定義的條件,則為 true;否則為 false。
Code
- public static void Main()
- {
- // Create an array of five Point
structures.- Point[] points = { new Point(100, 200),
- new Point(150, 250), new Point(250, 375),
- new Point(275, 395), new Point(295, 450) };
- Point first = Array.Find(points, ProductGT10);
- // Display the first structure found.
- Console.WriteLine("Found: X = {0},
Y = {1}", first.X, first.Y);- }
- // This method implements the test
condition for the Find- // method.
- private static bool ProductGT10(Point p)
- {
- if (p.X * p.Y > 100000)
- {
- return true;
- }
- else
- {
- return false;
- }
- }