简体   繁体   English

如何使用CancelEventArgs之类的事件?

[英]How events like CancelEventArgs can be used?

How can the event System.ComponentModel.CancelEventArgs be used? 如何使用事件System.ComponentModel.CancelEventArgs Suppose we have the following code: 假设我们有以下代码:

    public event CancelEventHandler EventTest = delegate { };

    public void MakeSomethingThatRaisesEvent()
    {
        CancelEventArgs cea = new CancelEventArgs();
        EventTest(this, cea);
        if (cea.Cancel)
        {
            // Do something
        }
        else
        {
            // Do something else
        }
    }

What happens if more than one delegate is registered on the event? 如果在活动中注册了多个代表,会发生什么? There is any way to get the results of all the subscribers? 有什么办法可以获得所有订阅者的结果吗?

This is used on Winforms (at least) sometimes. 这有时用于Winforms(至少)。 If not possible to get all values, they suppose only one subscriber to the event? 如果不能获得所有值,他们只假设该事件的一个订户?

To ask each subscriber separately, you need to access the list: 要单独询问每个订户,您需要访问该列表:

foreach (CancelEventHandler subHandler in handler.GetInvocationList())
{
     // treat individually
}

Then you can check each in turn; 然后你可以依次检查每一个; otherwise you just get the final vote. 否则你只是得到最后的投票。

Normally, in most cases, the class just allows multiple subscribers, but each gets the same instance of CancelEventArgs. 通常,在大多数情况下,该类只允许多个订阅者,但每个订阅者都获得相同的CancelEventArgs实例。

If any of the subscribers set Cancel to true, the operation will be treated as canceled. 如果任何订户将Cancel设置为true,则该操作将被视为已取消。

You can work around this by getting the invocation list, and sending an event to each subscriber, but this is not usually necessary. 您可以通过获取调用列表并向每个订阅者发送事件来解决此问题,但通常不需要这样做。

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

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