Skip to main content
 首页 » 编程设计

c#之如何在 C# 中声明委托(delegate)实例

2024年02月13日14zdz8207

private delegate void stopMachineryDelegate(); 
public stopMachineryDelegate StopMachinery; 
 
this.StopMachinery += new stopMachineryDelegate(painting); 

在上面第二行的例子中,我们创建的是委托(delegate)实例还是委托(delegate)变量?如果第二行创建了类型为 stopMachineryDelegate 的委托(delegate)实例,那么在第三行我们在做什么?

请您参考如下方法:

第一行用于定义您的委托(delegate)类型 (stopMachineryDelegate),作为不接受任何参数且不返回任何值的委托(delegate) (void)。

第二行声明了一个该类型的字段,名为 StopMachinery。此时,StopMachinery 为空。

第三行背后有一些语法糖。如果此时 StopMachinery 为空,它将创建该 MulticastDelegate 的新实例,然后将 painting 方法委托(delegate)添加到其调用列表中.

如果您只想为该字段分配一个委托(delegate),您可以简单地写:

 // implicitly wrap the `painting` method into a new delegate and  
 // assign to the `StopMachinery` field 
 this.StopMachinery = painting;   

另一方面,使用 += 允许您在调用 StopMachinery 时指定要调用的委托(delegate)列表:

 this.StopMachinery += painting;   
 this.StopMachinery += someOtherMethod;   
 this.StopMachinery += yetAnotherMethod;   

在后一种情况下,StopMachinery 委托(delegate)的调用将按照指定的顺序同步调用调用列表中的每个方法。