學(xué)會(huì)委托有哪些委托
2025.05.23 18:43 7
在編程領(lǐng)域,學(xué)會(huì)委托(Delegate)有多種類型,常見的有以下幾種:
實(shí)例方法委托
-
定義:用于引用對(duì)象的實(shí)例方法。
-
示例:
class Program { static void Main() { MyClass obj = new MyClass(); // 創(chuàng)建一個(gè)實(shí)例方法委托,指向obj的InstanceMethod Action del = obj.InstanceMethod; del(); // 調(diào)用委托,實(shí)際執(zhí)行obj的InstanceMethod } } class MyClass { public void InstanceMethod() { Console.WriteLine("這是實(shí)例方法"); } }
靜態(tài)方法委托
-
定義:用于引用類的靜態(tài)方法。
-
示例:
class Program { static void Main() { // 創(chuàng)建一個(gè)靜態(tài)方法委托,指向StaticClass的StaticMethod Action del = StaticClass.StaticMethod; del(); // 調(diào)用委托,實(shí)際執(zhí)行StaticClass的StaticMethod } } class StaticClass { public static void StaticMethod() { Console.WriteLine("這是靜態(tài)方法"); } }
帶參數(shù)的委托
-
定義:可以傳遞參數(shù)給所引用的方法。
-
示例:
class Program { static void Main() { // 創(chuàng)建一個(gè)帶參數(shù)的委托,指向Add方法 Func<int, int, int> del = Add; int result = del(3, 5); Console.WriteLine(result); // 輸出8 } static int Add(int a, int b) { return a + b; } }
泛型委托
-
定義:允許處理不同類型的數(shù)據(jù),同時(shí)保持類型安全。
-
示例:
class Program { static void Main() { // 創(chuàng)建一個(gè)泛型委托,指向Print方法 Action<int> del = Print; del(10); // 輸出10 } static void Print<T>(T value) { Console.WriteLine(value); } }
多播委托
-
定義:可以組合多個(gè)委托,按順序依次調(diào)用所引用的方法。
-
示例:
class Program { static void Main() { Action del1 = Method1; Action del2 = Method2; // 創(chuàng)建多播委托 Action combined = del1 + del2; combined(); } static void Method1() { Console.WriteLine("方法1"); } static void Method2() { Console.WriteLine("方法2"); } }