Func<T, TResult> 委托:有一个传入参数T,返回类型为TResult的委托。
Func<T1, T2, TResult> 委托:有两个传入参数:T1与T2,返回类型为TResult。
Func<T1, T2,...,Tn, TResult> 委托:有n传入参数:T1至Tn,返回类型为TResult。
Func都是有返回类型的,如果我们的方法没有返回类型该怎么办呢?这时Action就要闪亮登场了。
匿名方法:
Func<int, int, int> func = delegate(int m, int n) { return m + n; }; int sum = func(1, 3); Console.WriteLine(sum);
lambda 表达式
Func<int, int, int> func = (m, n) => m + n; int sum = func(1, 3); Console.WriteLine(sum);
Action 委托:没有传入参数,也没有返回类型,即Void。
Action<T> 委托:传入参数为T,没有返回类型。
Action<T1, T2> 委托:两个传入参数,分别为T1与T2,没有返回类型。
匿名方法:
Action<int, int> action = delegate(int m, int n) // 无参 直接delegate { Console.WriteLine(m + n); }; action(1, 3);
Lambda表达式:
Action<int, int> action = (m, n) => Console.WriteLine(m + n); action(1, 3);
例子:
class ActionFuncCls { private static void Add(int m, int n) { Console.WriteLine(m + n); } /// <summary> /// Action委托 /// </summary> public static void CallAction() { ///@无参 //Action action = () => Console.WriteLine("abc"); //action(); //@方法一 //Action<int, int> action = new Action<int,int>(Add); //action(1, 3); //@方法二 //Action<int, int> action = delegate(int m, int n) // 无参 直接delegate //{ // Console.WriteLine(m + n); //}; //action(1, 3); //@方法三 //Action<int, int> action = (int m, int n) => Console.WriteLine(m + n); Action<int, int> action = (m, n) => Console.WriteLine(m + n); action(1, 3); } /// <summary> /// Func 委托 /// </summary> public static void CallFunc() { ///@无参 //Func<int> func = () => 5; //int sum = func(); //Console.WriteLine(sum); //@方法一 //Func<int, int, int> func = new Func<int, int, int>(Add); //int sum = func(1, 3); //Console.WriteLine(sum); //@方法二 //Func<int, int, int> func = delegate(int m, int n) //{ // return m + n; //}; //int sum = func(1, 3); //Console.WriteLine(sum); //@方法三 Func<int, int, int> func = (int m, int n) => m + n; //Func<int, int, int> func = (m, n) => m + n; int sum = func(1, 3); Console.WriteLine(sum); } }