private delegate void stopMachineryDelegate();
public stopMachineryDelegate StopMachinery;
this.StopMachinery += new stopMachineryDelegate(painting);
在上面第二行的例子中,我们是创建一个委托实例还是一个委托变量?如果第二行创建了 stopMachineryDelegate 类型的委托实例,那么在第三行中我们在做什么?
On the second line you are declaring a variable of type stopMachineryDelegate
. But at this point the variable is still unassigned having holding a default value of null
.
On the third line you are assigning a value to this variable by creating a new instance of the delegate pointing to the painting
function.
So once this variable is assigned you could use it to invoke the function it is pointing to:
this.StopMachinery();
which will basically invoke the painting
method in the same class.
First line is used to define your delegate type (stopMachineryDelegate
), as a delegate accepting no parameters and returning no values (void
).
Second line is declaring a field of that type, named StopMachinery
. At that point, StopMachinery
is null.
The third line has some syntactic sugar behind it. If StopMachinery
is null at that point, it will create a new instance of that MulticastDelegate
, and then add the painting
method delegate to its invocation list.
If you only wanted to assign a single delegate to that field, you could have simply written:
// implicitly wrap the `painting` method into a new delegate and
// assign to the `StopMachinery` field
this.StopMachinery = painting;
On the other hand, using +=
allows you to specify a list of delegates to be invoked when you invoke StopMachinery
:
this.StopMachinery += painting;
this.StopMachinery += someOtherMethod;
this.StopMachinery += yetAnotherMethod;
In the latter case, invocation of the StopMachinery
delegate will invoke each of the methods in the invocation list, synchronously, in the order they were specified.