繁体   English   中英

在我的 C# 项目中,我想在特定条件下退出 Method1,并执行 Method2 而不再返回 Method1。 我怎样才能做到这一点?

[英]In my C# project,I want to exit Method1 on a specific condition, and execute Method2 without coming back to Method1 again. How can I do that?

在我的 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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM