且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将多个事件处理程序绑定到按钮?

更新时间:2023-10-06 23:20:52

在C#中,事件总是被添加到事件实例的调用列表中使用operator + =。没有别的办法。您应该在同一个事件实例(即:相同的对象实例,同一个事件成员)上使用此运算符,然后再使用一次。 C#中最短的代码(在较新的版本中使用 lambda 语法和类型推断它甚至更好)可能是这样的:

In C#, the event is always added to the invocation list of an event instance using the operator +=. There is no any other way. You simply should use this operator on the same event instance (that is: same object instance, same event member) more then once. The shortest possible code in C# (in newer versions using lambda syntax and type inference it's even better) is probably this:
myButton.Click += delegate(object sender, System.EventArgs eventArgs) {
   // do something
}

myButton.Click += delegate(object sender, System.EventArgs eventArgs) {
   // do something else
}



它会通过向其添加两个处理程序来创建与首次创建多播委托相同的效果,然后使用+ =将此多播委托实例添加到事件实例的调用列表中。我会把它留给你的家庭锻炼。 :-)



您可能会感到困惑,因为您只使用设计师添加了活动。与设计师一起做所有事情都很糟糕。如果你开始用自己的双手进行真正的编程,了解事情是如何工作的,那会更好。此外,在很多情况下使用设计师是完全不切实际的。



-SA