在我的程序中,我有一個方法,它有運行時總是使用的代碼。但是,在相同的方法中,我有if
語句,它們基於狀態機分支代碼。我們只是(爲了簡單)說它是由兩個值組成的。是否有可能逃離`if ... elseif ... else`語句,比如`break`對循環有用,對於方法用`return`呢?
using System;
using System.Console;
int stateA = 1;
int stateB = 1;
void Main() {
while (true) {
Method();
}
}
void Method() {
Console.WriteLine("This will always be printed no matter what happens.");
if (stateA == 1 && stateB == 1)
{
Console.WriteLine("State 1");
stateB = 2;
// goto endofifstatement;
}
elseif (stateA == 1 && stateB == 2)
{
Console.WriteLine("State 2");
stateA = 2;
// goto endofifstatement;
}
else {
Console.WriteLine("Resetting States...")
stateA = 1;
stateB = 2;
// goto endofifstatement;
}
// endofifstatement:
Console.WriteLine("This will always also be printed no matter what happens.");
Console.WriteLine("");
}
現在。此代碼現在的問題是,if...elseif...else
塊的所有三個部分都將在每次循環迭代中運行。
當然,有幾種方式,我可以解決這個問題:
- 獨立(封裝)的
if...elseif....else
語句轉換成其自己的方法,並使用return
爆發。 - 更換
if
和elseif
塊的內容和表達式,但這隻適用於這種情況。如果我們有幾百個案例會發生什麼? - 使用
goto
,但沒有人真的再使用它了。 (注意上面的代碼片段) - 使用多個
switch...case
或IF語句,嵌套在對方內部。
問:
是否有可能逃出的if...elseif...else
聲明像break
確實給一個循環,並return
確實爲方法呢?
因此,對於上面的例子中,輸出應該是:
This will always be printed no matter what happens.
State 1
This will always also be printed no matter what happens.
This will always be printed no matter what happens.
State 2
This will always also be printed no matter what happens
This will always be printed no matter what happens.
Resetting States...
This will always also be printed no matter what happens
,重複,而不是:
This will always be printed no matter what happens.
State 1
State 2
Resetting States...
This will always also be printed no matter what happens
This will always be printed no matter what happens.
State 1
State 2
Resetting States...
This will always also be printed no matter what happens
AAAND重複。另外,如果我們將這個擴展爲兩個以上的變量和可能的值,它應該能夠保持,即使在CPU速度的範圍內,因爲我們只是基本上脫離了一個塊。
也許只是在'for'循環和'if'' else'之上的計數器? –
你是什麼意思所有3個分支與當前代碼一起運行?我認爲你需要重新考慮這一點。 – itsme86
@ itsme86是的。我只是意識到。 – aytimothy