C# 多次附加事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19314983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attaching an event handler multiple times
提问by BhushanK
I am new to C#. I just wanted to know whether attaching event handler multiple times can cause unexpected result?
我是 C# 的新手。我只是想知道多次附加事件处理程序是否会导致意外结果?
Actually in my application i am attaching an event handler to an event like
实际上在我的应用程序中,我将一个事件处理程序附加到一个事件中,例如
cr.ListControlPart.Grid.CurrentCellActivated += new EventHandler(Grid_CurrentCellActivated);
and this line of code called multiple times in the code.
而这行代码在代码中多次调用。
采纳答案by James
If you keep attaching event handlers then it will be raised once for each time you've attached the handler. This means:
如果您继续附加事件处理程序,则每次附加处理程序时都会引发一次。这意味着:
- If you only need it to be raised once then assign one handler.
- If you attach the same handler 4 times then it will be called 4 times.
- 如果您只需要引发一次,则分配一个处理程序。
- 如果您附加相同的处理程序 4 次,那么它将被调用 4 次。
Looking at your code, instead of hooking into the CurrentCellActivated
event multiple times it would make more sense to subscribe to a general CellActivated
event once.
查看您的代码,CurrentCellActivated
与其多次挂钩事件,不如订阅一次一般CellActivated
事件更有意义。
回答by Alessandro D'Andria
Try it yourself:
自己试试:
static class Program
{
static event EventHandler MyEvent;
static void Main()
{
// registering event
MyEvent += Program_MyEvent;
MyEvent += Program_MyEvent;
MyEvent += Program_MyEvent;
MyEvent += Program_MyEvent;
MyEvent += Program_MyEvent;
// invoke event
MyEvent(null, EventArgs.Empty);
Console.ReadKey();
}
static void Program_MyEvent(object sender, EventArgs e)
{
Console.WriteLine("MyEvent fired");
}
}
Output:
输出:
MyEvent fired
MyEvent fired
MyEvent fired
MyEvent fired
MyEvent fired
回答by Rajesh Subramanian
You can prevent it by unsubscribing before adding it,
您可以通过在添加之前取消订阅来防止它,
Object.Event -= EventHandler(method);
Object.Event += EventHandler(method);
if can be done, prevent it by always subscribe events in one place say constructor
如果可以完成,请通过始终在一个地方订阅事件来防止它说构造函数