[英]How to cancel the execution of a method?
考慮我在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;
希望它能回答你的問題。
如果由於錯誤而想退出方法,可以拋出這樣的異常:
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;
}
MyCustomException繼承自Exception類。
你在談論多線程嗎?
或類似的東西
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;
}
有幾種方法可以做到這一點。 如果您認為是錯誤,可以使用return
或throw
。
您可以使用return語句設置一個guard子句:
public void Method1(){
bool isOK = false;
if(!isOK) return; // <- guard clause
// code here will not execute...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.