Func 是 C# 预先定义好的委托之一。它封装了一个有 TResult 类型的返回值的方法。

Func 可以有 0~16 个参数。

public delegate TResult Func<in T1, ... in T16, out TResult>(T1 arg1, ... T16 arg16);

in 在这里表示逆变

使用例:

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

与其他 delegate 一样,Func 也可以和匿名函数lambda 表达式一起使用:

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

See also