C# 如何取消方法的执行?
假设我在C#中执行了一个方法“Method1”。 一旦执行进入方法,我会检查一些条件,如果其中任何一个条件为false,那么应该停止Method1的执行。我如何做到这一点,即在满足某些条件时,可以执行方法 但我的代码是这样的C# 如何取消方法的执行?,c#,C#,假设我在C#中执行了一个方法“Method1”。 一旦执行进入方法,我会检查一些条件,如果其中任何一个条件为false,那么应该停止Method1的执行。我如何做到这一点,即在满足某些条件时,可以执行方法 但我的代码是这样的 int Method1() { switch(exp) { case 1: if(condition) //do the following. ** else /
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;
希望它能回答你的问题
编辑:
如果由于错误而要退出该方法,可以引发如下异常:
throw new Exception( "My error message" );
如果要使用值返回,则应像以前一样使用所需的值返回:
return 0;
如果它是您需要的异常,您可以在调用您的方法的方法中使用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;
}
MyCustomException继承自Exception类。您可以使用return语句设置一个guard子句:
public void Method1(){
bool isOK = false;
if(!isOK) return; // <- guard clause
// code here will not execute...
}
公共作废方法1(){
bool-isOK=false;
如果(.ISOK)返回;//< P>有几种方法。您可以使用<代码>返回<代码>或<代码>投掷< /代码>,如果您认为是错误的话。 您是在谈论多线程吗?
或者类似的
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;
}
int方法1(int-inputvalue)
{
/*检查条件*/
如果(输入值<20)
{
//这会将执行移回调用函数
返回0;
}
如果(输入值>100)
{
//这会“抛出”一个错误,可能会停止调用函数中的执行。
抛出新ArgumentOutOfRangeException();
}
//否则,继续在method1中执行
/*…做事*/
返回值;
}
“==true”?怎么样((myCondition==true)==true)?停止执行后是否要退出程序?还是要返回调用方法?或者如果(!condition 1 | |!condition 2)return;