A question about delegates
I am开发者_运维技巧 trying to read some code that I did not write. In the main body of the class, there is the following 2 lines.
// RenderingService callbacks
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);
Now, I have never used delegates before in C#, but read that there is three steps (declaration, instantiation and invocation). The 2nd lines looks like the declaration and the 1st line looks like the first step in instantiation. Inside the constructor of the class, there is the following line:
//Inside the constructor
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;
where renderingServiceResponsesDelegate is the parameter passed by the constructor. So that would be the second part of the instantiation. Is this correctly understood? I was confused by the order of things. Is is possible to instantiate it like that in c# before it has been declared?
The second line is the declaration of the type RenderingServiceResponsesDelegate
.
The first line is the declaration of a variable with that type. It is not the instantiation.
The line inside the constructor assigns a value to the variable - but in your example this value is received from elsewhere. Instantiation means creating an instance, which is often done with the new
keyword. In your example you haven't provided the code where the instantiation is performed.
This is the declaration of the delegate type:
public delegate void RenderingServiceResponsesDelegate(Collection<RenderingServiceResponse> responses);
This is the declaration of a member that is of that delegate type:
protected RenderingServiceResponsesDelegate renderingServiceResponsesDelegate;
This is the assignment of a previously instanciated instance to that member:
this.renderingServiceResponsesDelegate = renderingServiceResponsesDelegate;
renderingServiceResponsesDelegate
points to a specific method of a object instance or a static method.
The previous instanciation could have looked like this:
SomeClassThatHasTakesTheDelegateInstance c = new SomeClassThatHasTakesTheDelegateInstance (new RenderingServiceResponsesDelegate (this.SomeMethodThatMatchesTheDelegateSignature));
An invocation would then look like this:
this.renderingServiceResponsesDelegate(someResponses);
精彩评论