委托的一些笔记

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 }

 
原文地址:https://www.cnblogs.com/zuiailiuruoying/p/13305972.html