繁体   English   中英

如何在C#中声明委托实例?

[英]How to declare instance of delegate in C#?

private delegate void stopMachineryDelegate();
public stopMachineryDelegate StopMachinery;

this.StopMachinery += new stopMachineryDelegate(painting);

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

在第二行,您将声明一个stopMachineryDelegate类型的变量。 但此时变量仍然未分配,并保持默认值null

在第三行,您将通过创建指向painting函数的委托的新实例为此变量赋值。

因此,一旦分配了此变量,您就可以使用它来调用它指向的函数:

this.StopMachinery();

这将基本上调用同一类中的painting方法。

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

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

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

如果您只想将单个委托分配给该字段,您可以简单地写:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM