如何取消方法的执行?

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

但我的代码是这样的,

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

使用return语句。

 if(!condition1) return; if(!condition2) return; // body... 

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

 if( myCondition || !myOtherCondition ) return; 

希望它能回答你的问题。

编辑:

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

 throw new Exception( "My error message" ); 

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

 return 0; 

如果它是您需要的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; } 

MyCustomExceptioninheritance自Exception类。

你在谈论multithreading吗?

或类似的东西

 int method1(int inputvalue) { /* checking conditions */ if(inputvalue < 20) { //This moves the execution back to the calling function return 0; } if(inputvalue > 100) { //This 'throws' an error, which could stop execution in the calling function. throw new ArgumentOutOfRangeException(); } //otherwise, continue executing in method1 /* ... do stuff ... */ return returnValue; } 

有几种方法可以做到这一点。 如果您认为是错误,可以使用returnthrow

您可以使用return语句设置一个guard子句:

 public void Method1(){ bool isOK = false; if(!isOK) return; // <- guard clause // code here will not execute... }