日期:2014-05-17  浏览次数:20843 次

C#委托事件

Delegate 是在.NET1.0 的时候就已经存在了的特性,因为在准备总结Lambda 表达式的时候发现自己对Delegate 还没有深刻的理解,所以打算先对Delegate 进行整理一下。

?????? Delegate 中文译为“委托”,MSDN 中对Delegate 是这样进行解释的“C# 中的委托 类似于CC++ 中的函数指针。使用委托使程序员可以将方法引用封装在委托对象内 。然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。与CC++ 中的函数指针不同,委托是面向对象、类型安全的,并且是安全的 。”

?????? 我们来通过一个Demo 来进行理解:

class Program

??? {

??????? static void OtherClassMethod()

??????? {

??????????? Console .WriteLine("Delegate an other class's method" );

??????? }

??????? static void Main(string [] args)

??????? {

??????????? var test = new TestDelegate ();

??????????? test.delegateMethod = new TestDelegate .DelegateMethod (test.NonStaticMethod);

??????? ???? test.delegateMethod += new TestDelegate .DelegateMethod (TestDelegate .StaticMethod);

??????????? test.delegateMethod += Program .OtherClassMethod;