C#-Func<>
C#-Func<>
与C#-Action十分相似, Func<> 也是c#内置的委托类型,不同的是, Func<> 只能用来引用具有返回值的方法,也就是说,在使用它时,至少需要在尖括号内指定一种类型,当仅指定一种类型时,表示引用具有返回值但没有参数的方法,当指定多种类型时,其中最后一个类型表示返回值类型,前面的表示所引用方法的参数列表的类型。
有一下两个简单的例子:
指定一个类型时
1 static void Main(string[] args)
2 {
3 Func<string> a=Gettomorrow;
4 Console.WriteLine(a());
5
6 }
7 public static string Gettomorrow()
8 {
9 return DateTime.Now.AddDays(1).Date.ToString();
10 }
11
12 // 2020/8/5 0:00:00
当指定两个类型时
1 static void Main(string[] args)
2 {
3 Func<int, double> calc = Factorial;
4 Console.WriteLine(calc(5));
5
6 }
7
8 public static double Factorial(int num)
9 {
10 //求一个整数的阶乘
11 int res = 1;
12 for(int i=2;i<=num;i++)
13 {
14 res *= i;
15 }
16 return res;
17 }
18 // 120
与 Action 一样, Func<> 最多支持16个参数。
漫思

浙公网安备 33010602011771号