如何取消方法的执行?

Syn*_*ter 10 c#

考虑我在C#中执行方法'Method1'.一旦执行进入方法,我检查几个条件,如果它们中的任何一个是假的,那么应该停止执行Method1.我怎么能这样做,即可以在满足某些条件时执行方法.

但我的代码是这样的,

int Method1()
{
    switch(exp)
    {
        case 1:
        if(condition)
            //do the following. **
        else
            //Stop executing the method.**
        break;
        case2:
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 31

使用该return声明.

if(!condition1) return;
if(!condition2) return;

// body...
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以说 `if(!condition1 || !condition2) return;` (3认同)

Jes*_*sen 13

我想这就是你要找的东西.

if( myCondition || !myOtherCondition )
    return;
Run Code Online (Sandbox Code Playgroud)

希望它能回答你的问题.

编辑:

如果由于错误而想退出方法,可以抛出这样的异常:

throw new Exception( "My error message" ); 
Run Code Online (Sandbox Code Playgroud)

如果要返回值,则应该像以前一样返回所需的值:

return 0;
Run Code Online (Sandbox Code Playgroud)

如果它是您需要的Exception,您可以在调用方法的方法中使用try catch来捕获它,例如:

void method1()
{
    try
    {
        method2( 1 );
    }
    catch( MyCustomException e )
    {
        // put error handling here
    }

 }

int method2( int val )
{
    if( val == 1 )
       throw new MyCustomException( "my exception" );

    return val;
}
Run Code Online (Sandbox Code Playgroud)

MyCustomException继承自Exception类.