原文地址(http://msdn.microsoft.com/zh-cn/library/ms173172(v=VS.90).aspx

委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似。与 C 中的函数指针不同,委托是面向对象的、类型安全的和保险的。委托的类型由委托的名称定义。(这可真是大水冲了龙王庙,本人以前用过C++,早说是函数指针不就明白了嘛......既然看了,就耐心地看完...)

void 的方法。

public delegate void Del(string message); 

告诉编译器 Del 是一个指向返回值为void、有1个string参数的函数的指针,哦不,是委托,呵呵

声明完了类型之后,还需要给它赋值才能够运转的,那我们来定义一个返回值为void、有1个string参数的函数吧

public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}

接下来,我们来实例化这个 Del 委托

// Instantiate the delegate.
Del handler = DelegateMethod;

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

可以将一个实例化的委托视为被包装的方法本身来调用该委托。

我来白话一下,handler是Del委托的实例,指向了DelegateMethod() 这个方法,因此调用handler(string)和调用DelegateMethod(string)是等价的

为什么要这么做?这样一来,你可以把handler作为参数进行传递,可以在你需要调用的时候,在任何地方调用到DelegateMethod方法

何时使用委托而不使用接口。

下面的示例方法使用 Del 类型作为参数:

public void MethodWithCallback(int param1, int param2, Del callback)
{
callback("The number is: " + (param1 + param2).ToString());
}

然后可以将上面创建的委托传递给该方法:

MethodWithCallback(1, 2, handler);

在控制台中将收到下面的输出:

The number is: 3

此功能特别强大,因为委托的方法可以使用任意数量的参数。

考虑下列声明:

public class MethodClass
{
public void Method1(string message) { }
public void Method2(string message) { }
}

加上前面显示的静态 DelegateMethod,现在我们有三个方法可由 Del 实例进行包装。

例如:

 

MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;

//Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;

例如:

//remove Method1
allMethodsDelegate -= d1;

// copy AllMethodsDelegate while removing d2
Del oneMethodDelegate = allMethodsDelegate - d2;

例如,为了找出委托的调用列表中的方法数,您可以编写下面的代码:

int invocationCount = d1.GetInvocationList().GetLength(0);

由于两个类都支持 GetInvocationList,所以上面的代码在两种情况下都适用。

事件(C# 编程指南)。

例如:

delegate void Delegate1();
delegate void Delegate2();
static void method(Delegate1 d, Delegate2 e, System.Delegate f)
{
// Compile-time error.
//Console.WriteLine(d == e);

// OK at compile-time. False if the run-time type of f
// is not the same as that of d.
System.Console.WriteLine(d == f);
}

转自:http://www.cnblogs.com/zdkjob/articles/2270543.html

相关文章: