我在C#方面有很好的经验,但现在我在java项目上工作,所以我参观了java功能。关于Labeled和Unlabeled中断(它也可以在JavaScript中使用),我很头疼这是非常好的功能,在某些情况下缩短了很多时间使用带标记的中断。
我的问题是,在C#或C ++中标记中断的最佳选择是什么,看看我认为我们可以使用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#中执行此操作时:
我使用的是flag而不是label:
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 ++中有标记符号的已知替代方法或标记为continue?
答案 0 :(得分:1)
除了goto之外,重构C#逻辑可能更好,比如
public static String SearchInTwoDimArray()
{
int[,] arr = {
{1,2,3,4},
{5,6,7,8},
{12,50,7,8} };
int searchFor = 50;
int[] index = { -1, -1 };
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;
return("Found " + searchFor + " at raw " + index[0] + " column " + index[1]);
}
}
}
return("Not Found");
// Console.ReadLine(); // put this line outside of the function call
}