.NET Framework委托的預(yù)定義方法介紹
.NET Framework開發(fā)環(huán)境對(duì)于開發(fā)人員來(lái)說(shuō)是一個(gè)非常實(shí)用的開發(fā)平臺(tái)。我們可以通過(guò)它來(lái)進(jìn)行WEB應(yīng)用程序的部署。前言:從.NET Framework2.0開始以來(lái),系統(tǒng)預(yù)定義的委托使使代碼看起來(lái)有點(diǎn)像“天書”,再加上匿名表達(dá)式,以及后面Lambda表達(dá)式的“摻和”,代碼就更加難懂了,于是自己就一點(diǎn)點(diǎn)查MSDN,到現(xiàn)在終于有點(diǎn)入門了。#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還包括從不帶任何參數(shù)到最多四個(gè)參數(shù)的重載?
1、public delegate void Action< T>(T obj )
封裝一個(gè)方法,該方法只采用一個(gè)參數(shù)并且不返回值。
Code
- Action< string> messageTarget;
- messageTarget = s => Console.
WriteLine(s);- messageTarget("Hello, World!");
2、public delegate TResult Func<TResult>()
封裝一個(gè)具有一個(gè)參數(shù)并返回 TResult 參數(shù)指定的類型值的方法。
類型參數(shù)T
此委托封裝的方法的參數(shù)類型。
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)
表示定義一組條件并確定指定對(duì)象是否符合這些條件的方法。
類型參數(shù)
T:要比較的對(duì)象的類型。
返回值
如果 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;
- }
- }


2009-08-18 11:08:24




