.NET Framework中预定义的委托

前言:从.NET Framework2.0开始以来,系统预定义的委托使使代码看起来有点像“天书”,再加上匿名表达式,以及后面Lambda表达式的“掺和”,代码就更加难懂了,于是自己就一点点查MSDN,到现在终于有点入门了。
常用委托:
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


2、public delegate TResult Func<TResult>()
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
类型参数T
   此委托封装的方法的参数类型。
TResult
   此委托封装的方法的返回值类型

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(100200), 
            
new Point(150250), new Point(250375), 
            
new Point(275395), new Point(295450) };

        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;
        }
    }

 

 

posted @ 2009-03-06 11:08  stu_acer  阅读(332)  评论(0编辑  收藏  举报