我有一些方法可以从其他一些方法中调用.当在某些方法中执行某个操作时,我想回到第一个方法并跳过剩下的代码.目前,我booleans用来检查程序的"状态",但我想避免这种情况,因为这些方法应该是void从本质上说它们不需要返回任何东西.我发现了类似的东西,goto但只能在同一种方法中使用.
问题:有没有办法在C#中以不同的方法跳转到代码中的特定点?我在其他语言上发现了一些东西,但在C#上却没有.
现在的情况:
    void test1()
    {
        bool status = test2();
        if (!status)
            return; // the other stuff will not get done
        Debug.WriteLine("Initialization OK");
    }
    bool test2()
    {
        bool status = test3();
        if (!status)
            return false; // the other stuff will not get done
        // do other stuff 
        return true;
    }
    bool test3()
    {
        if (xxx)
            return false; // the other stuff will not get done
        else
            // do other stuff 
            return true;
    }
通缉情况:
    void test1()
    {
        test2();
        // do other stuff
        Debug.WriteLine("Initialization OK");
        GOTOHERE:
             Debug.WriteLine("Initialization NOT OK");
    }
    void test2()
    {
        test3();            
        // do other stuff 
    }
    void test3()
    {
        if (xxx)
            **GOTOHERE**; // Go directly to the location in test1() so that all unnecessary code is skipped
        // do other stuff
    }
我很惊讶地发现C#确实支持GOTO命令.但它旨在允许从深嵌套循环中退出.
本文对此进行了解释并提供了大量示例:https: //www.dotnetperls.com/goto
然而
除非你在1970年仍在编码,否则使用GOTO被认为是非常糟糕的做法.它使代码维护非常困难.它甚至会导致问题和性能问题,并使JIT编译器的生命变得更加困难.
现在的声明只是过于原始,这是一个太多的邀请,使一个人的程序混乱.
Edsger W. Dijkstra
| 归档时间: | 
 | 
| 查看次数: | 8174 次 | 
| 最近记录: |