两个有用的委托:Func和Action

转载至:http://www.cnblogs.com/jhxk/articles/1828322.html

 Func和Action是两个泛型委托,为什么说他们有用呢?是由于这两个自带的委托在很多时候可以省去我们自定义委托的工作。

    1.Func

     该委托有5个重载形式,区别仅在于他所指向的方法的签名的参数个数,分别如下:

  • Func<TResult>
  • Func<T,TResult>
  • Func<T1,T2,TResult>
  • Func<T1,T2,T3,TResult>
  • Func<T1,T2,T3,T4,TResult>

     其中T,T1,..T4是委托指向的方法的参数的类型,TResult为方法的返回类型

     举个例子,在学习委托的时候需要用委托来写个计算平方的小程序,您可以这样实现:

test自定义委托
class Program
   {
        private delegate int CalcSquare(int size);
 
       public static void Main()
       {
            CalcSquare cal = Square;
 
           Console.Write("the square of {0} is {1}", 10, cal(10));
       }
        private  static int Square(int size)
       {
            return size*size;
       }
    }

首先需要声明一个委托:CalcSquare,如果用Func这个内置的委托来实现,则可以如下:

test用Func实现
class Program
   {
        public static void Main()
       {
            Func<int,int> cal = Square;
 
           Console.Write("the square of {0} is {1}", 10, cal(10));
       }
        private  static int Square(int size)
       {
            return size*size;
       }
    }

可见,省去了自定义委托的那步。

您可能会说,Func的重载都是需要有返回值的,但是如果我的方法不需要返回值呢?OK,这就该轮到Action出场了。

2.Action

    同样,Action也有以下几种重载形式:

  • Action
  • Action<T>
  • Action<T1,T2>
  • Action<T1,T2,T3>
  • Action<T1,T2,T3,T4>

    稍稍改下上面的例子:

test自定义委托
    class Program
   {
        private delegate void CalcSquare(int size);
 
       public static void Main()
       {
            CalcSquare cal = size=>Console.WriteLine("the square od {0} is {1}", size, size * size);
 
           cal(10);
       }
    }

    同样的您需要先声明一个委托。

test用Action实现
    class Program
   {
        public static void Main()
       {
            Action<int> cal = size=>Console.WriteLine("the square od {0} is {1}", size, size * size);
 
           cal(10);
       }
    }

   总结:Func和Action是两个比较有用的委托,能解决我们的很多需求。当然,有时候如果您觉得给委托起个容易理解的名字很重要,也可以去自定义委托,毕竟工作量也不大,是吧。

 【2010-4-21】在4.0这两个委托又有了变化,现在可支持达16个参数!

原文地址:https://www.cnblogs.com/jshchg/p/2101391.html