在msdn上有委托的基本用法,介绍的很详细,链接如下:
http://msdn2.microsoft.com/zh-cn/library/900fyy8e(VS.80).aspx
我以前一直对C#中委托的用法心存疑惑,这两天发了点时间,好好的研究了一下
以下边代码为例:
using System;
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
// Declare delegate -- defines required signature:
delegate void SampleDelegate(string message);
class MainClass
{
// Regular method that matches signature:
static void SampleDelegateMethod(string message)
{
Console.WriteLine(message);
}
static void Main()
{
// Instantiate delegate with named method:
SampleDelegate d1 = SampleDelegateMethod;
// Instantiate delegate with anonymous method:
SampleDelegate d2 = delegate(string message)
{
Console.WriteLine(message);
};
// Invoke delegate d1:
d1("Hello");
// Invoke delegate d2:
d2(" World");
}
}
与这段代码对应的IL视图为:
代码的这句:
delegate void SampleDelegate(string message);
其中的SampleDelegate在IL中被编译为一个类,而且SampleDelegate派生于MulticastDelegate。我们如果不看上边那段代码的IL视图,很容易对代码中的这段代码的用法疑惑
1SampleDelegate d1 = SampleDelegateMethod;
2SampleDelegate d1 = new SampleDelegate(SampleDelegateMethod);
上边两段代码的功能是一样的,只是第2句更容易理解。
2SampleDelegate d1 = new SampleDelegate(SampleDelegateMethod);