在我的c#项目中,我想在特定条件下退出Method1并执行另一个方法(Method2),而不返回到Method1。我想防止使用跳转语句(goto)。我该怎么做呢?
我的简化代码看起来像
public void Method1 ()
{
if (condition==true)
{
Method2() // Here at this point I want to exit Method1 and execute Method2. That means after executing Method2 the program shall not return to Method1. How can I do that?
}
//some code
}
正如在注释中提到的,您可以在方法调用后返回。
if (condition == true)
{
Method2();
return;
}
或者,您可以为if
语句添加else
,以便在进入if
时仅运行Method2()
。
if (condition == true)
{
Method2();
}
else
{
//Do something
}
另一种方法是对两个方法使用相同的返回类型(除了void)(如果适用),并像下面这样返回。
if (condition == true)
{
return Method2();
}