如何实现可取消事件? [英] How do I implement a cancelable event?
问题描述
在System.ComponentModel中,有一个名为CancelEventArgs的类,其中包含可以在事件侦听器中设置的Cancel成员。 MSDN上的文档解释了如何使用它来从监听器中取消事件,但是如何使用它来实现我自己的可取消事件?有没有办法在每个监听器触发之后检查取消成员,或者我必须等待事件触发所有监听器之后?
In System.ComponentModel, there's a class called CancelEventArgs which contains a Cancel member that can be set in event listeners. The documentation on MSDN explains how to use that to cancel events from within a listener, but how do I use it to implement my own cancelable events? Is there a way to check the Cancel member after each listener fires, or do I have to wait until after the event has fired all its listeners?
推荐答案
要依次查看每个监听器,您需要通过GetInvocationList手动获取处理程序:
To check each listener in turn, you need to manually get the handlers via GetInvocationList:
class Foo
{
public event CancelEventHandler Bar;
protected void OnBar()
{
bool cancel = false;
CancelEventHandler handler = Bar;
if (handler != null)
{
CancelEventArgs args = new CancelEventArgs(cancel);
foreach (CancelEventHandler tmp in handler.GetInvocationList())
{
tmp(this, args);
if (args.Cancel)
{
cancel = true;
break;
}
}
}
if(!cancel) { /* ... */ }
}
}
这篇关于如何实现可取消事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!