[英]goto difficulties with C#
為什么會出現以下編譯器錯誤:
//錯誤CS0159:沒有這樣的標簽“ lbl_proc_20”
使用以下代碼:
//JUST A DUMMY CODE TO ILLUSTRATE THE CONCEPT
int a = resultOfFunction1();
int b = resultOfFunction2();
//10+ Local variables that are calculated depending on the results above
if (a < 10)
{
switch (b)
{
case 0:
//Actions for A<10, B=0, using local variables
break;
case 1:
double c = someFunction(a, b); //In real code involves calculations based on a and b
if(c > 10.0)
goto lbl_proc_20; //error CS0159: No such label 'lbl_proc_20' within the scope of the goto statement
//Actions for A<10, B=1, using local variables
break;
default:
//Actions for A<10, B=Other, using local variables
break;
}
}
else if (a < 20)
{
lbl_proc_20:
switch(b)
{
case 0:
//Actions for A<20, B=0, using local variables
break;
case 1:
//Actions for A<20, B=1, using local variables
break;
case 2:
//Actions for A<20, B=2, using local variables
break;
default:
//Actions for A<20, B=Other, using local variables
break;
}
}
else if (a < 30)
{
switch(b)
{
case 0:
//Actions for A<30, B=0, using local variables
break;
case 1:
//Actions for A<30, B=1, using local variables
break;
case 2:
//Actions for A<30, B=2, using local variables
break;
default:
//Actions for A<30, B=Other, using local variables
break;
}
}
為什么我在goto語句上遇到錯誤以及如何使其生效?
編輯:更改示例以說明實際的代碼。
您只能使用goto
跳轉到goto
范圍內的標簽。 從描述錯誤CS0159
的文檔中:
在goto語句的范圍內找不到goto語句引用的標簽。
盡管標簽存在,但是您不能從if
塊跳到else
塊。 else
的代碼與包含goto
。
現在是重組代碼的時候了,因此不需要goto
。
編輯
您應該嘗試簡化邏輯。 多個函數比goto
語句更可取。
您可能要考慮的一種選擇是Windows Workflow Foundation 。 這是一個非常簡潔的工具,可讓您直觀地將邏輯表示為流程圖。 然后,WWF將生成處理您指定的邏輯所必需的代碼。 這可能適用,因為它看起來就像您正在創建某種類型的有限狀態機或類似過程一樣。
作為對“不使用goto怎么做”的回應
bool pretendA20 = false;
if (a < 10)
{
switch (b)
{
case 0:
//Actions for A<10, B=0, using local variables
break;
case 1:
double c = someFunction(a, b); //In real code involves calculations based on a and b
if(c > 10.0)
{
//goto lbl_proc_20;
pretendA20 = true;
break;
}
//Actions for A<10, B=1, using local variables
break;
default:
//Actions for A<10, B=Other, using local variables
break;
}
}
if ((a >= 10 && a < 20) || pretendA20)
{
//lbl_proc_20:
switch(b)
{
C#語言規范(第249頁的第8章)指出:
如果當前函數成員中不存在具有給定名稱的標簽,或者goto語句不在標簽范圍內,則會發生編譯時錯誤。 該規則允許使用goto語句將控制權移出嵌套范圍,但不能移入嵌套范圍。
在您的情況下,標簽lbl_proc_20
與goto
不在同一個范圍內,並且您試圖將控制權轉移到另一個嵌套范圍內。
您可以從這里獲取語言規范:
http://www.microsoft.com/zh-cn/download/details.aspx?id=7029
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.