关于代表的问题

时间:2010-11-30 08:31:16

标签: c# .net delegates

我正在尝试阅读一些我没写过的代码。在班级的主体中,有以下两行。

// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);

现在,我从未在C#中使用过委托,但是读到有三个步骤(声明,实例化和调用)。第二行看起来像声明,第一行看起来像实例化的第一步。在类的构造函数中,有以下行:

//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;

其中renderingServiceResponsesDelegate是构造函数传递的参数。这将是实例化的第二部分。这是否正确理解?我对事物的顺序感到困惑。是否可以在声明之前将其实例化为c#中的内容?

2 个答案:

答案 0 :(得分:2)

第二行是类型 RenderingServiceResponsesDelegate的声明。

第一行是具有该类型的变量的声明。这不是实例化。

构造函数中的行为变量赋值 - 但在您的示例中,此值是从其他位置接收的。实例化意味着创建实例,通常使用new关键字来完成。在您的示例中,您尚未提供执行实例化的代码。

答案 1 :(得分:2)

这是委托类型的声明:

public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);

这是该委托类型的成员声明:

 protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;

这是将先前实例化的实例分配给该成员:

this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;

renderingServiceResponsesDelegate指向对象实例或静态方法的特定方法。

之前的实例可能看起来像这样:

SomeClassThatHasTakesTheDelegateInstance c = new SomeClassThatHasTakesTheDelegateInstance (new RenderingServiceResponsesDelegate (this.SomeMethodThatMatchesTheDelegateSignature));

调用将如下所示:

this.renderingServiceResponsesDelegate(someResponses);