编辑
2025-09-23
C#
00

目录

Action 委托
无参数的 Action
带参数的 Action
多个参数的 Action
Func 委托
无参数的 Func
带参数的 Func
多个参数的 Func
使用 Action 和 Func 作为方法参数
Action 作为参数
Func 作为参数
总结

在C#中,委托是一种类型,它安全地封装了一个方法的引用。委托可以用来实现回调函数和事件订阅。C# 提供了两种内置的委托类型:ActionFunc。这些内置委托使得代理使用起来更加简单和灵活,有了这个基本不用自己声明delegate 了。

Action 委托

Action 是一个不返回值的委托类型,它可以有0到16个参数。当你需要一个执行操作但不返回结果的委托时,可以使用 Action

无参数的 Action

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Action printHello = () => Console.WriteLine("Hello, World!"); printHello(); Console.ReadKey(); } } }

image.png

带参数的 Action

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Action<string> greet = (name) => Console.WriteLine($"Hello, {name}!"); greet("Alice"); Console.ReadKey(); } } }

image.png

多个参数的 Action

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Action<string, int> customGreet = (name, number) => { for (int i = 0; i < number; i++) { Console.WriteLine($"Hello, {name}!"); } }; customGreet("Rick", 3); Console.ReadKey(); } } }

image.png

Func 委托

Func 委托类型代表一个返回值的方法,它可以有0到16个输入参数。Func 委托的最后一个类型参数是返回类型。

无参数的 Func

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Func<int> getRandomNumber = () => new Random().Next(); int number = getRandomNumber(); Console.WriteLine(number); Console.ReadKey(); } } }

image.png

带参数的 Func

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Func<int, int, int> add = (a, b) => a + b; int sum = add(5, 10); Console.WriteLine(sum); Console.ReadKey(); } } }

image.png

多个参数的 Func

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { Func<string, string, string> concatenate = (a, b) => a + b; string result = concatenate("Hello", "World"); Console.WriteLine(result); Console.ReadKey(); } } }

image.png

使用 Action 和 Func 作为方法参数

你可以将 ActionFunc 作为参数传递给方法,这在实现回调或策略模式时非常有用。

Action 作为参数

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { PerformAction(() => Console.WriteLine("Action performed")); Console.ReadKey(); } static void PerformAction(Action action) { Console.WriteLine("Before action"); action(); Console.WriteLine("After action"); } } }

image.png

Func 作为参数

C#
namespace AppActionFunc { internal class Program { static void Main(string[] args) { UseFunc((x, y) => x * y); Console.ReadKey(); } static void UseFunc(Func<int, int, int> func) { int result = func(2, 3); Console.WriteLine($"Result is: {result}"); } } }

image.png

总结

ActionFunc 是C#中非常强大的内置委托类型,它们提供了一种简洁的方式来引用方法。通过使用这些委托,你可以编写更灵活和可重用的代码。在实现诸如回调、LINQ查询、异步编程等功能时,ActionFunc 委托都是不可或缺的工具。掌握它们的使用将大大提高你编写高效、清晰和维护性好的C#代码的能力。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!