C#委托

1、什么是委托:

委托是一个类型安全的对象,它指向程序中另一个以后会被调用的方法(或多个方法)。它类似C语言里的函数指针,但它是类型安全的。

委托类型包含3个重要的信息:

  • 它所调用的方法的名称
  • 该方法的参数
  • 该方法的返回值类型(可选)

当一个委托对象被创建并提供了上述信息后,它可以在运行时动态调用其指向的方法

2.在C#中定义委托

假设我们创建一个Manipulation的委托,它可以指向任何输入两个整数返回一个整数的方法

1 public delegate int Manipulation(int x,int y);

通过Microsoft .NetFramework IL disassembler查看器查看IL

ildasm.exe路径:"C:Program Files (x86)Microsoft SDKsWindowsv8.1AinNETFX 4.5.1 Toolsildasm.exe"

 //看如下代码:
  sealed class Manipulation : System.MulticastDelegate
    {
        public int Invoke(int x, int y);
        public IAsyncResult BeginInvoke(int x, int y, AsyncCallback cb, object state);
        public int EndInvoke(IAsyncResult result);
    }

委托还可以指向包含任意数量 的out或ref参数(以及用params关键字标记的数组参数)

如有委托类型如下:

public delegate string AnotherFunction(out bool a,ref bool b,int c);

2、泛型委托:

 /// 假设我们希望定义一个委托类型来调用任何返回Void并且接受单个参数的方法。
 /// 如果这个参数可能会不同,我们就可以通过类型参数来构建。

首先声明一个委托:

public delegate void MyGenericDelegate<T>(T arg);

再创建两个方法,一个传入字符串,一个传入数字

1     static void StringTarget(string arg)
2         {
3             Console.WriteLine("arg in uppercase is :{0}",arg.ToUpper());
4         }
5 
6         static void IntTarget(int arg)
7         {
8             Console.WriteLine("++arg is:{0}",++arg);
9         }
1       //注册目标
2             MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget);
3             strTarget("Some string Data");

输出:

arg in uppercase is :SOME STRING DATA

原文地址:https://www.cnblogs.com/zhaotianff/p/5974472.html