定义
委托是一种类型(type),该类型定义(封装)一种函数(或函数签名)。你可以用任何与该签名匹配的函数实例化委托。
委托主要用来给其它方法传入函数类型的参数。与c和c++中函数的指针类似,但它是面向对象,type safe, and secure。
其它版本:A delegate is a type that defines a method signature.
Adelegateis 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);
相关资料:Delegates,Using Delegates When to Use Delegates Instead of Interfaces
原文链接: https://www.cnblogs.com/season2009/archive/2012/11/02/2749939.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/67957
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!