如何取消可以取消的活动?

aba*_*hev 3 .net c# events

请帮助我实现一个事件,处理程序可以取消它.

public class BuildStartEventArgs : EventArgs
{
    public bool Cancel { get; set; }
}

class Foo
{
    public event EventHandler<BuildStartEventArgs> BuildStart;

    private void Bar()
    {
        // build started
        OnBuildStart(new BuildStartEventArgs());
        // how to catch cancellation?
    }

    private void OnBuildStart(BuildStartEventArgs e)
    {
        if (this.BuildStart != null)
        {
            this.BuildStart(this, e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 5

您需要修改此代码:

private void Bar()
{
    // build started
    OnBuildStart(new BuildStartEventArgs());
    // how to catch cancellation?
}
Run Code Online (Sandbox Code Playgroud)

这样的事情:

private void Bar()
{
    var e = new BuildStartEventArgs();
    OnBuildStart(e);
    if (!e.Cancel) {
      // Do build
    }
}
Run Code Online (Sandbox Code Playgroud)

.NET中的类具有引用语义,因此您可以看到对事件参数所做的任何更改引用.