C# 中的 Func 代理 和 Action代理(一)

C# 包含内建的 泛型代理 Func 和 Action, 所以大多数情况下都没有必要自己手动定义一个 delegate(代理)

Func 和 Action 都位于 System 命名空间内, 它允许有0-15个参数 和 1个返回值 

以下是Func的函数签名

namespace System
{    
    public delegate TResult Func<in T, out TResult>(T arg);
}

<>符号内的最后一个参数类型将作为输出的返回值类型,剩下的其他参数被作为是输入参数类型

 

下图是一个 带有两个参数 一个返回值的 Func 代理

 

 

 

Func<int, int, int> sum;

你可以赋值任意一个包含两个int类型的参数一个int返回值的函数给sum 

class Program
{
    static int Sum(int x, int y)
    {
        return x + y;
    }

    static void Main(string[] args)
    {
        Func<int,int, int> add = Sum;

        int result = add(10, 10);

        Console.WriteLine(result); 
    }
}

一个泛型Func代理可以包含0-16个不同类型的参数,不过,这16个参数的最后一个必定是返回值的类型,以下的例子展示了 没有参数、有一个返回值的函数

Func<int> getRandomNumber;

你也可以通过delegate关键字赋值一个匿名方法给Func 代理  如下

Func<int> getRandomNumber = delegate()
                            {
                                Random rnd = new Random();
                                return rnd.Next(1, 100);
                            };

Func 与 Lambda表达式

Func<int> getRandomNumber = () => new Random().Next(1, 100);

//Or 

Func<int, int, int>  Sum  = (x, y) => x + y;
 Points to Remember :
  1. Func is built-in delegate type.
  2. Func delegate type must return a value.
  3. Func delegate type can have zero to 16 input parameters.
  4. Func delegate does not allow ref and out parameters.
  5. Func delegate type can be used with an anonymous method or lambda expression.
posted @ 2021-03-29 20:12  一个新星的诞生  阅读(68)  评论(0)    收藏  举报