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
(3)多播委托
delegate的妙用-多播委托,此時會按順序依次調用引用的所有方法,下面是多播委托的例子
using System;namespace DelegateDemo
{delegate void MyDelegate(string s);class Program{static void Method1(string s){Console.WriteLine($"Method1 hello {s}");}static void Method2(string s){Console.WriteLine($"Method2 hello {s}");}static void Method3(string s) =>//"=>"用于定義只有一句的方法Console.WriteLine($"Method3 hello {s}");static void Main(string[] args){MyDelegate myDele = new MyDelegate(Method1); myDele += Method2;//多播委托-增加引用myDele("myDele"); Console.WriteLine($"-------1");myDele += Method2;//多播委托-增加引用myDele("myDele");Console.WriteLine($"-------2");myDele += Method3;myDele("myDele");Console.WriteLine($"-------3");myDele -= Method2;//多播委托-刪除引用myDele("myDele");Console.Read();}}
}
輸出
Method1 hello myDele
Method2 hello myDele
-------1
Method1 hello myDele
Method2 hello myDele
Method2 hello myDele
-------2
Method1 hello myDele
Method2 hello myDele
Method2 hello myDele
Method3 hello myDele
-------3
Method1 hello myDele
Method2 hello myDele
Method3 hello myDele
下面通過兩個例子來說明Action委托的用法。
2、Action無參數的例子
using System;namespace ActionDemo1
{delegate void MyDelegate(); //1、委托類型 class Program{static void Method(){Console.WriteLine("Method 被調用" );}static void Main(string[] args){MyDelegate myDel = new MyDelegate(Method);//2、委托實例化myDel();//3、委托對象的調用Action showActioMethod = Method;showActioMethod();Console.ReadLine();}}
}
輸出
Method 被調用
Method 被調用
3、Action有參數的例子
using System;namespace ActionDemo2
{delegate void MyDelegate(string s); //1、定義委托類型 class Program{static void Method(string s) {Console.WriteLine("Method 被調用,輸入:" + s);}static void Main(string[] args){MyDelegate myDel = new MyDelegate(Method);//2、委托實例化myDel("delegate委托");//3、委托對象的調用Action<string> showActioMethod = Method;showActioMethod("Action委托");Console.ReadLine();}}
}
?輸出
Method 被調用,輸入:delegate委托
Method 被調用,輸入:Action委托
可以看到,使用 delegate
進行委托操作通常需要三步,而使用 Action
進行委托時,只需兩步即可完成。尤其是無需提前定義委托類型這一點,非常關鍵。這樣,在閱讀代碼時,我們不需要跳轉到委托類型的定義部分,從而提升了代碼的可讀性和簡潔性。
參考
C#內置泛型委托:Action委托 - .NET開發菜鳥 - 博客園
Action 委托 (System) | Microsoft Learn
叩響C#之門 (16.2 多播委托)(豆瓣)