【发布时间】:2015-06-19 23:54:06
【问题描述】:
我在 C# 方面有很好的经验,但现在我从事 java 项目,所以我参观了 java 特性。我对 Labeled 和 Unlabeled break(它也可以在 JavaScript 中使用)很感兴趣,这是一个非常好的功能,并且在某些情况下可以缩短很多使用带标签的 break 的时间。
我的问题是,在 C# 或 C++ 中标记 break 的最佳替代方案是什么,看起来我认为我们可以使用 goto 关键字从任何范围退出,但我不喜欢它。我尝试用 Java 编写代码来使用标记的 break 在二维数组中搜索数字,这很容易:
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?
【问题讨论】:
-
投票结束 - 基于意见。一个好的编译器应该优化代码以打破循环,而不管常见的布局如何。最好的方法是最易读、最安全的方法。
-
带标签的 break 只比普通的 'goto' 稍微好一点,所以 如果 你喜欢在 Java 中这样编码,你应该对 C# 'goto' 没有问题。
-
我更喜欢 goto 而不是额外的标志。模仿 labeled break 可能是 goto 仍然有用的最后一种情况。