在c#foreach循环中catch {}和catch {continue;}有什么区别?
问题描述:
foreach (Widget item in items)
{
try
{
//do something...
}
catch { }
}
foreach (Widget item in items)
{
try
{
//do something...
}
catch { continue; }
}
答
catch { continue; }
将导致代码在新的迭代上启动,跳过循环内的catch
块之后的任何代码。
答
编译器会忽略它。这是从反射器。
public static void Main(string[] arguments)
{
foreach (int item in new int[] { 1, 2, 3 })
{
try
{
}
catch
{
}
}
foreach (int item in new int[] { 1, 2, 3 })
{
try
{
}
catch
{
}
}
}
答
其他答案告诉你在给定的代码片段中会发生什么。使用catch子句作为循环中的最终代码,没有功能差异。如果你有catch子句后面的代码,那么没有“continue”的版本将执行该代码。 continue
是break
的stepbrother,它将循环体的其余部分短路。与continue
,它跳到下一个迭代,而break
完全退出循环。无论如何,为自己展示你的两种行为。
for (int i = 0; i < 10; i++)
{
try
{
throw new Exception();
}
catch
{
}
Console.WriteLine("I'm after the exception");
}
for (int i = 0; i < 10; i++)
{
try
{
throw new Exception();
}
catch
{
continue;
}
Console.WriteLine("this code here is never called");
}
答
如果您的样本是逐字记录的,那么我会说“没有区别”!
但是,如果您在发现后执行语句,那么它就完全不同了! catch { continue; }
将跳过catch块之后的任何东西! catch{}
仍然会执行catch块后的语句!
这可能是由编译器完成的优化。上面的示例代码非常具体。如果在catch块之后(在第二个foreach循环中)有语句,那么你应该看到继续。所以你不能说,总是继续被忽略。 – SysAdmin 2010-06-10 19:06:58
@SysAdmin - 我很好奇你为什么发表了这个评论,当我的回答没有提到'继续'将永远被忽略。 – ChaosPandion 2010-06-11 04:11:28