委托

定义

委托是一种类型(type),该类型定义(封装)一种函数(或函数签名)。你可以用任何与该签名匹配的函数实例化委托。

委托主要用来给其它方法传入函数类型的参数。与c和c++中函数的指针类似,但它是面向对象,type safe, and secure。

其它版本:A delegate is a type that defines a method signature.

     A delegate is a type that safely encapsulates a method

              delegate 关键字用于声明可用来封装命名方法的引用类型

定义理解

委托类型由委托的名字定义, 如下面的示例定义了一个委托(类型),它的名字叫Del,它封装的是“接受一个字符串参数,返回void类型”的函数。

public delegate void Del(string message);

再看下.net framework 中的示例代(注释也是来自微软):

//封装一个不具有参数但却返回 TResult 参数指定的类型值的方法。
public delegate TResult Func<out TResult>();

继承关系

委托类型继承自 Delegate,也就是说Del的父类是Delegate。

上面的Delegate和委托定义中的delegate不一样,前者是类型,后者是关键字。

与Class的类比

本质上定义委托和定义Class没有区别,可以把Del看成普通的类。

委托实例化及调用

// Instantiate the delegate.
Del handler = DelegateMethod;

// Call the delegate.
handler("Hello World");

//也可以这样调用
Del handler = new Del(DelegateMethod);

相关资料:DelegatesUsing Delegates When to Use Delegates Instead of Interfaces

原文地址:https://www.cnblogs.com/season2009/p/2749939.html