说我有两个EventHandler:
private void button1_click(object sender, EventArgs e)
{
//Do first stuffs
button2_click(sender, e);
//Do second stuffs
}
private void button2_click(object sender, EventArgs e)
{
//Do something
if(myCondition) return; //Also return in button1_click
//Do something else
}
如果button1_click
已停止并返回,有没有办法在//Do second stuffs
中退回并跳过button2_click
部分?
我正在寻找一种方法,而不是使用公开的bool
变量检查myCondition
中的button2_click
是true
答案 0 :(得分:2)
我的建议是将每个处理程序的有意义部分提取到可以独立调用并且可以具有有用返回值的方法中。这对于第二个按钮的处理程序尤为重要,因为button1的处理程序也依赖于它。
在提取代码后,您可以将提取的方法转换为布尔函数,并且可以依赖返回值来继续您的过程。
private void button1_click(object sender, EventArgs e)
{
ThingToDoForButton1();
}
private void button2_click(object sender, EventArgs e)
{
ThingToDoForButton2();
}
private void ThingToDoForButton1()
{
// do something
if (ThingToDoForButton2())
{
// do something else
}
}
private bool ThingToDoForButton2()
{
//Do something
if(/* some condition */) return false;
//Do something else
return true;
}
当然,您可以在提取后为方法提供有意义的名称,并考虑将代码分解为其他较小的函数,如果"做某事"和"做别的事情"零件并非无足轻重。
答案 1 :(得分:0)
我想,你想要这样的东西
private void button1_click(object sender, EventArgs e)
{
//Do first stuffs
button2_click(sender, e);
//Reading the tag value of sender object that is assigned in that case
if (!(bool)(sender as Button).Tag)
return;
//Do second stuffs
}
private void button2_click(object sender, EventArgs e)
{
//Do something
//Since sender object is button1 in the example
Button button = sender as Button;
button.Tag = true;
if (myCondition)
{
button.Tag = false;
return;
}//Also return in button1_click
//Do somthing else
}
答案 2 :(得分:0)
您可以像这样使用CancelEventArgs Class:
private void button1_click(object sender, EventArgs e)
{
//Do first stuffs
var e1 = new CancelEventArgs();
button2_click(sender, e1);
if(e1.Cancel)
{
return;
}
//Do second stuffs
}
private void button2_click(object sender, CancelEventArgs e)
{
//Do somthing
if(myCondition)
{
e.Cancel = true;
return;
}
//Do somthing else
}