1. 程式人生 > 實用技巧 >委託的一些筆記

委託的一些筆記

1、理解委託的一種好方式是把委託視為給方法的簽名和返回型別指定名稱;

2、定義委託基本上是定義一個新類,所以可以在定義類的任何相同地方定義委託,也就是說可以在一個類的內部定義委託,也可以在任何類的外部定義委託,還可以在名稱空間中把委託定義為頂級物件;

3、使用委託時,也類似使用類,首先要定義委託(包括訪問修飾符、返回值、引數):

  ①public delegate string InMethodInvoker() ---------返回為string,無引數

  ②public delegate void OutPut(int i)  -----------返回void,存在一個int型引數

4、方法必須和委託定義時的簽名的一致

 ① 

int i=9;

InMethodInvoker inMethodInvoker = new InMethodInvoker(i.ToString);

Console.WriteLine($"String is { inMethodInvoker()}");

 ②

public static void MyMethod(int i)
{
     Console.WriteLine($"String is {i.ToString()}");
}

static void Main(string[] args)
{
     OutPut output 
= new OutPut(MyMethod);
   output (999); 

   Console.ReadKey();
}

5、為了減少輸入量,在需要委託例項的每個位置可以只傳送地址的名稱,稱為委託推斷,上述委託例項化可以改為:

InMethodInvoker inMethodInvoker = i.ToString;

OutPut output = MyMethod ;

6、委託的簡單示例,細細品吧

 1 using System;
 2 
 3 namespace DelegateConsole
 4 {
 5     class MathOperations
 6     {
7 public static double MultiplyByTwo(double value) => value * 2; 8 public static double Square(double value) => value * value; 9 } 10 11 class Program 12 { 13 delegate double DoubleOp(double x); 14 static void Main(string[] args) 15 { 16 DoubleOp[] operations = 17 { 18 MathOperations.MultiplyByTwo, 19 MathOperations.Square 20 }; 21 22 for (int i=0; i < operations.Length; i++) 23 { 24 Console.WriteLine($"Using operations[{i}]:"); 25 ProcessAndDisplayNumber(operations[i], 2.0); 26 ProcessAndDisplayNumber(operations[i], 7.94); 27 ProcessAndDisplayNumber(operations[i], 1.414); 28 Console.WriteLine(); 29 } 30 Console.ReadKey(); 31 } 32 33 private static void ProcessAndDisplayNumber(DoubleOp action, double value) 34 { 35 double result = action(value); 36 Console.WriteLine($"Value is {value},result of operation is {result}"); 37 } 38 } 39 }