我在C#中有很好的體驗,但現在我在java項目上工作,所以我參加了java功能的導覽。我喜歡標記和未標記的中斷(它也可以在JavaScript中使用),這是非常好的功能,它縮短了在某些情況下使用標記中斷的時間。標記和未標記的中斷,繼續在C#或C++中
我的問題是,在C#或C++中標記爲break的最佳選擇是什麼,看起來我認爲我們可以使用goto關鍵字從任何範圍出去,但我不喜歡它。我試着寫在Java代碼中使用帶標籤的它很容易在數量上搜索在二維數組:
public static void SearchInTwoDimArray()
{
// here i hard coded arr and searchFor variables instead of passing them as a parameter to be easy for understanding only.
int[][] arr = {
{1,2,3,4},
{5,6,7,8},
{12,50,7,8}
};
int searchFor = 50;
int[] index = {-1,-1};
out:
for(int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
{
if (arr[i][j] == searchFor)
{
index[0] = i;
index[1] = j;
break out;
}
}
}
if (index[0] == -1) System.err.println("Not Found!");
else System.out.println("Found " + searchFor + " at raw " + index[0] + " column " + index[1]);
}
當我嘗試這樣做,在C#:
- 這是可能的,因爲我說的之前使用goto
我使用的標誌,而不是標籤:
public static void SearchInTwoDimArray() { int[,] arr = { {1,2,3,4}, {5,6,7,8}, {12,50,7,8} }; int searchFor = 50; int[] index = { -1, -1 }; bool foundIt = false; for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { if (arr[i, j] == searchFor) { index[0] = i; index[1] = j; foundIt = true; break; } } if(foundIt) break; } if (index[0] == -1) Console.WriteLine("Not Found"); else Console.WriteLine("Found " + searchFor + " at raw " + index[0] + " column " + index[1]); }
那麼它是唯一有效的方法嗎?或者在C#和C++中標記爲break或者標記爲continue的已知替代方法?
投票決定關閉 - 基於意見。一個好的編譯器應該優化代碼以打破循環,而不管常見的佈局如何。最好的方法是最可讀和最安全的方法。 –
帶標籤的中斷只比普通的'goto'略好,所以*如果*你喜歡在Java中這樣編碼,那麼你應該對C#'goto'沒有任何問題。 –
我更喜歡goto到額外的標誌。模仿**標籤的break **可能是goto仍然有用的最後一種情況。 –