C# 中泛型委託是什麼?
使用泛型委託,無需定義委託語句。它們在 System 名稱空間中定義。
可以使用型別引數定義泛型委託。例如 −
delegate T myDelegete<T>(T n);
示例
以下示例演示如何在 C# 中建立泛型委託 −
using System; using System.Collections.Generic; delegate T myDelegete<T>(T n); namespace GenericDelegateAppl { class TestDelegate { static int num = 5; public static int AddNum(int p) { num += p; return num; } public static int MultNum(int q) { num *= q; return num; } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); //calling the methods using the delegate objects nc1(50); Console.WriteLine("Value of Num: {0}", getNum()); nc2(10); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } }
廣告