C# 如何实施可以取消的事件?
帮助我实现一个事件,哪个处理程序可以取消它C# 如何实施可以取消的事件?,c#,.net,events,C#,.net,Events,帮助我实现一个事件,哪个处理程序可以取消它 public class BuildStartEventArgs : EventArgs { public bool Cancel { get; set; } } class Foo { public event EventHandler<BuildStartEventArgs> BuildStart; private void Bar() { // build started
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);
}
}
}
公共类BuildStartEventArgs:EventArgs
{
公共bool Cancel{get;set;}
}
福班
{
公共事件事件处理程序BuildStart;
专用空格键()
{
//开始构建
OnBuildStart(新的BuildStartEventArgs());
//如何捕捉取消?
}
BuildStart(BuildStartEventArgs e)上的专用void
{
if(this.BuildStart!=null)
{
this.BuildStart(this,e);
}
}
}
您需要修改此代码:
private void Bar()
{
// build started
OnBuildStart(new BuildStartEventArgs());
// how to catch cancellation?
}
对这样的事情:
private void Bar()
{
var e = new BuildStartEventArgs();
OnBuildStart(e);
if (!e.Cancel) {
// Do build
}
}
NET中的类具有引用语义,因此您可以看到对事件引用的参数对象所做的任何更改。在BuildStartEventArgs类上具有布尔Cancel属性。 让事件处理程序能够对此进行标记
private void Bar()
{
// build started
var args = new BuildStartEventArgs();
OnBuildStart(args);
if (args.Cancel)
{
// cancel
}
}
水果挞席水果挞< <代码>是多余的,框架已经提供了类——考虑使用它。< /P>在问题的示例中BueDistaTeVARGGS类上已经有了一个布尔取消属性。为什么不使用已经存在的SyraseTrangsARGS类?我会看BTW,是System.ComponentModel.CancelEventArgs:)谢谢你的提示。但是我的类有额外的属性,我只是没有在这里写它们。但是你可以从CancelEventArgs继承!谢谢我想这会很难。编程中的每件事都很难。。。似乎是这样:——)