Welcome

首页 / 软件开发 / C# / 委托揭秘

委托揭秘2010-01-26 cnblogs Old参考:

框架设计(第二版):CLR Via C#——15.4 委托揭秘(P281)

正文:

代码1-1,这是一个简单的委托使用。

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate
{
public class DelegateTest
{
protected delegate void MyDelegate();

private void TestMethod() { }

private void Method()
{
MyDelegate aMyDelegate = new MyDelegate(TestMethod);
Method(aMyDelegate);
}

private void Method(MyDelegate aMyDelegate)
{
if (aMyDelegate != null)
{
aMyDelegate();
}
}
}
}

代码1-1

从表面上看,委托似乎很容易使用:用C#的delegate关键字来定义,用我们都熟悉的new操作符来构造委托实例,用我们熟悉的方法调用语法来调用回调函数(不过要用引用了委托对象的变量来代替方法名)。

然而,实际情况比前面几个例子所演示的复杂得多。编译器和CLR做了大量的幕后工作来隐藏复杂性。本节将集中讲解编译器和CLR是如何实现委托的。掌握这些知识有助于我们理解委托,并学会如何更好地使用它们。与此同时,本节还要适当地介绍委托的其它一些特征。

首先重新查看下面这行代码:代码1-2

public delegate void MyDelegate();

代码1-2