C# 編程指南
命名方法(C# 編程指南) 委託可以與命名方法關聯。使用命名的方法對委託進行執行個體化時,該方法將作為參數傳遞,例如:C#複製代碼// Declare a delegate:delegate void Del(int x); // Define a named method:void DoWork(int k) { /* ... */ } // Instantiate the delegate using the method as a parameter:Del d = obj.DoWork;這被稱為使用命名的方法。使用命名方法構造的委託可以封裝靜態方法或執行個體方法。在以前的 C# 版本中,使用命名的方法是對委託進行執行個體化的唯一方式。但是,在建立新方法的系統開銷不必要時,C# 2.0 允許您對委託進行執行個體化,並立即指定委託將在被調用時處理的代碼塊。這些被稱為匿名方法(C# 編程指南)。
備忘作為委託參數傳遞的方法必須與委託聲明具有相同的簽名。委託執行個體可以封裝靜態或執行個體方法。儘管委託可以使用 out 參數,但不推薦將其用於多路廣播事件委託中,因為無法確定要調用哪個委託。
樣本 1以下是聲明及使用委託的一個簡單樣本。注意,委託 Del 和關聯的方法 MultiplyNumbers 具有相同的簽名 C#複製代碼// Declare a delegatedelegate void Del(int i, double j); class MathClass{ staticvoid Main() { MathClass m = new MathClass(); // Delegate instantiation using "MultiplyNumbers" Del d = m.MultiplyNumbers; // Invoke the delegate object. System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':"); for (int i = 1; i <= 5; i++) { d(i, 2); } } // Declare the associated method. void MultiplyNumbers(int m, double n) { System.Console.Write(m * n + " "); }}
輸出Invoking the delegate using 'MultiplyNumbers': 2 4 6 8 10
樣本 2在下面的樣本中,一個委託被同時映射到靜態方法和執行個體方法,並分別返回特定的資訊。C#複製代碼// Declare a delegatedelegate void Del(); class SampleClass{ publicvoid InstanceMethod() { System.Console.WriteLine("A message from the instance method."); } staticpublicvoid StaticMethod() { System.Console.WriteLine("A message from the static method."); }} class TestSampleClass{ staticvoid Main() { SampleClass sc = new SampleClass(); // Map the delegate to the instance method: Del d = sc.InstanceMethod; d(); // Map to the static method: d = SampleClass.StaticMethod; d(); }}
輸出A message from the instance method. A message from the static method. (來源:msdn )