C# Func委托和Action委托的用法(附带实例)
C# 中内置类型的委托有 Func 和 Action,程序设计师可以很容易地使用,省去了自定义委托,让工作更便利。
【实例 1】这是一个一般委托,将字符串改为大写的实例。
【实例 2】将实例 1 改为 Func 委托重新设计。
【实例 3】使用 Action 设计 Add() 和 Sub() 委托。
C# Func委托
Func 被定义在 System 命名空间内,可以有 0 到多个输入参数和 1 个输出参数,在系列参数中最后 1 个参数被视为是输出参数。其定义如下:namespace System { public delegate TResult Func<in T, TResult>(T arg); }
【实例 1】这是一个一般委托,将字符串改为大写的实例。
static string UpperString(string inputString) { return inputString.ToUpper(); } Func<string, string> convertBrand = UpperString; // 实体化委托和指定引用方法 string brand = "bmw"; Console.WriteLine(convertBrand(brand)); // 输出结果 delegate string ConvertMethod(string str); // 声明委托执行结果为:
BMW
【实例 2】将实例 1 改为 Func 委托重新设计。
static string UpperString(string inputString) { return inputString.ToUpper(); } Func<string, string> convertBrand = UpperString; // Func委托 string brand = "bmw"; Console.WriteLine(convertBrand(brand));执行结果与实例 1 相同。从上述程序可以看到我们省略了声明委托。
C# Action委托
Action 委托和 Func 委托相同,也是定义在 System 命名空间内定义的。其实功能也相同,两者的不同点主要是 Action 没有回传值,也就是说数据类型是 void。【实例 3】使用 Action 设计 Add() 和 Sub() 委托。
static void Add(int x, int y) { Console.WriteLine($"{x} + {y} = {x + y}"); } static void Sub(int x, int y) { Console.WriteLine($"{x} - {y} = {x - y}"); } Action<int, int> Math; // Action委托 Math = Add; Math(4, 3); // Add(4, 3) Math = Sub; Math(4, 3); // Sub(4, 3)执行结果为:
4 + 3 = 7
4 - 3 = 1