这篇的主要目的是用一些例子展示如何使用Func。
Func其实是一个内置的委托,它带来了一些函数式编程特性,并有助于减少代码冗长。
Func只能包含0 ~ 16个输入参数,且必须有一个返回类型。(Func委托有16个重载。)
例子一
//1.FuncExp1:不带参数的方法 static string GetMessage() { return "Hello there!"; } static void FuncExp1() { Func<string> sayHello = GetMessage; Console.WriteLine(sayHello()); }
测试结果如下:
例子二
//2.FunExp2:带两个参数的方法 static int Sum(int x, int y) { return x + y; } static void FuncExp2() { Func<int, int, int> Add = Sum; Console.WriteLine(Add(20, 30)); }
测试结果如下:
例子三
//3.FunExp3:带三个参数的方法 static int Sum2(int x, int y, int z) { return x + y + z; } static void FuncExp3() { Func<int, int, int, int> Add = Sum2; int result = Add(20, 30, 40); Console.WriteLine(result); }
测试结果如下:
例子四
Lambda表达式写法
static void Lambda1() { Func<int, int, int, int> Add = (x, y, z) => x + y + z; int result = Add(20, 30, 40); Console.WriteLine(result); }
例子五
//6.c# Func Linq Where static void LabmdaWithWhere() { Func<string, bool> HasThree = str => str.Length == 3; string[] words = { "sky", "forest", "wood", "cloud", "falcon", "owl" , "ocean", "water", "bow", "tiny", "arc" }; IEnumerable<string> threeLetterWords = words.Where(HasThree); //IEnumerable<string> three = words.Where(str => str.Length == 3);这种写法,看起来是不是很熟悉 foreach (var word in threeLetterWords) { Console.WriteLine(word); } }
测试结果如下:
例子六
//7.c# list of Func delegates static void ListofFunDelegates1() { var vals = new int[] { 1, 2, 3, 4, 5 }; Func<int, int> square = x => x * x; var res = vals.Select(square); //var result = vals.Select(q => q * q);这种写法,看起来是不是很熟悉 Console.WriteLine(string.Join(",", res)); }
测试结果如下:
例子七
static void ListofFunDelegates2() { var vals = new int[] { 1, 2, 3, 4, 5 }; Func<int, int> square = x => x * x; Func<int, int> cube = x => x * x * x; Func<int, int> inc = x => x + 1; var fns = new List<Func<int, int>> { inc, square, cube }; foreach (var fn in fns) { var res = vals.Select(fn); //var result = vals.Select(q => q * q);这种写法,看起来是不是很熟悉 Console.WriteLine(string.Join(",", res)); } }
测试结果如下:
参考网址如下:
https://zetcode.com/csharp/func/
本地代码在CSharpBasic\FuncTutorial