开发者

How events like CancelEventArgs can be used?

开发者 https://www.devze.com 2022-12-08 15:34 出处:网络
How can the event System.ComponentModel.CancelEventArgs be used? Suppose we have the following code: public event CancelEventHandler EventTest = delegate { };

How can the event System.ComponentModel.CancelEventArgs be used? 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开发者_JAVA技巧 the subscribers?

This is used on Winforms (at least) sometimes. 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.

If any of the subscribers set Cancel to true, the operation will be treated as canceled.

You can work around this by getting the invocation list, and sending an event to each subscriber, but this is not usually necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消