为事件设置方法是否会重置旧方法或在其事件列表中添加另一个方法?
我对在 .NET 中设置事件有点困惑。
我有设置为 MouseDown 的方法,如下所示。
if theTool = TMakerTool.tmtSelect then
begin
MouseDown += new System.Windows.Forms.MouseEventHandler(@SelectMouseDown);
Cursor := Cursors.Arrow;
end
else
begin
MouseDown += new System.Windows.Forms.MouseEventHandler(@Maker_MouseDown);
Cursor := Cursors.Cross;
end;
每次触发 mouseup 时都会调用上面的代码。因为代码只是将 MouseDown 事件设置为一个方法,所以它会重置已设置的旧方法还是保留它以及其事件列表中的另一个事件方法...
I am little confused about setting events in .NET.
I have methods that is set to MouseDown as follows.
if theTool = TMakerTool.tmtSelect then
begin
MouseDown += new System.Windows.Forms.MouseEventHandler(@SelectMouseDown);
Cursor := Cursors.Arrow;
end
else
begin
MouseDown += new System.Windows.Forms.MouseEventHandler(@Maker_MouseDown);
Cursor := Cursors.Cross;
end;
Above code is called everytime a mouseup is fired. Because the code is just setting MouseDown event to a method, will it reset the old method that was already set or keep it and just another event method in its event list...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以回答“这取决于”,但是,如果事件是根据 .NET 准则设计的,则按照您的方式添加事件意味着将其添加到事件处理程序列表中,而则不然删除旧的处理程序。对于所有 .NET 自己的事件来说确实如此,并且对于任何其他精心设计的事件也应该如此。
如果要从列表中删除事件,请使用
-=
运算符。如果您自己定义事件,则可以通过覆盖
add
访问器或remove
访问器来覆盖此行为。在这种情况下,您有责任正确存储事件处理程序。然而,这几乎不需要手动完成。I could answer "it depends", however, if events are designed according to the .NET guidelines, adding an event the way you do, means adding it to a list of event handlers and not remove the old handlers. This is certainly true for all .NET's own events and should be true for just about any other well designed event.
If you want to remove an event from the list, use the
-=
operator.If you define an event yourself, you can override this behavior by overriding the
add
-accessor or theremove
-accessor. In such a case you are responsible for proper storing of the event handlers. However, this is hardly ever necessary to do by hand.