C#中Action的用法
Action 是 C# 中委托的一种,用于封装无返回值的方法。它引用的方法不能有返回值,但可以有零个或多个参数。相比delegate委托,Action 委托的优点是不必显式定义封装无参数过程的委托,使代码更加简洁和易读。
1、delegate-委托
先简单介绍一下关键字delegate
(1)delegate用来定义一种变量类型,特别的地方在于这种类型只能指向方法。两个关键点:①输入参数(个数、类型、顺序);②返回值。
(2)delegate的例子
using System;namespace DelegateDemo
{delegate void MyDelegate(string s);//1、委托类型的定义:指向输入参数是字符串且无返回值的方法class Program{static void Method(string s){Console.WriteLine($"hello {s}");}static void Main(string[] args){MyDelegate myDele = new MyDelegate(Method); //2、委托的实例化myDele("myDele"); //3、委托的调用myDele.Invoke("myDele.Invoke");Console.Read();}}
}
输出
hello myDele
hello myDele.Invoke
下面通过两个例子来说明Action委托的用法。
2、Action无参数的例子
using System;namespace ActionDemo1
{delegate void MyAction(); //1、委托类型 class Program{static void ActionMethod(){Console.WriteLine("ActionMethod 被调用" );}static void Main(string[] args){MyAction myDel = new MyAction(ActionMethod);//2、委托实例化myDel();//3、委托对象的调用Action showActioMethod = ActionMethod;showActioMethod();Console.ReadLine();}}
}
输出
ActionMethod 被调用
ActionMethod 被调用
3、Action有参数的例子
using System;namespace ActionDemo2
{delegate void MyAction(string s); //1、定义委托类型 class Program{static void ActionMethod(string s) {Console.WriteLine("ActionMethod 被调用,输入:" + s);}static void Main(string[] args){MyAction myDel = new MyAction(ActionMethod);//2、委托实例化myDel("自定义委托");//3、委托对象的调用Action<string> showActioMethod = ActionMethod;showActioMethod("Action委托");Console.ReadLine();}}
}
输出
ActionMethod 被调用,输入:自定义委托
ActionMethod 被调用,输入:Action委托
可以看到,使用 delegate
进行委托操作通常需要三步,而使用 Action
进行委托时,只需两步即可完成。尤其是无需提前定义委托类型这一点,非常关键。这样,在阅读代码时,我们不需要跳转到委托类型的定义部分,从而提升了代码的可读性和简洁性。
参考
C#内置泛型委托:Action委托 - .NET开发菜鸟 - 博客园
Action 委托 (System) | Microsoft Learn