![](/img/trans.png)
[英]Can I write a C# method that will terminate execution of anyone who calls it (within the same class)?
[英]How to terminate a method execution Midway in C#?
當達到特定條件時,我需要退出 方法 。 達到退出Condition
后,不應執行其他代碼行。 我嘗試使用Environment.Exit(0)
的最佳方法是什么,但這在我的邏輯上引起了問題 。
除非處於循環狀態,否則Exit(0)
似乎不起作用
我們有兩種可能性:正常( return
)和異常( throw
)終止:
public static int Factorial(int value) {
// We can't compute factorial for negative and too large values
if (value < 0 || value > 12)
throw new ArgumentOutOfRangeException(nameof(value)); // Abnormal termination
if (value == 0)
return 1; // Normal termination: special case in which we know the answer
...
}
“ return”語句退出條件塊以及循環和方法。
public void myMethod(int a){
if( 1 == a) {
return;
}
// do something with a
}
正如有些人在我之前說過的那樣,返回是必經之路。 這是一個示例,其中if語句比較兩個整數,如果相等則返回:
public void isEqual(int a, int b) {
if (a == b) {
Console.WriteLine("Integers are equal");
return; //Return to executing the rest of the program.
}
else {
Console.WriteLine("Integers are not equal");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.