如果你有一个for循环:
for(i=0;i<10;i++){}
现在,当 i==5
时,如何在不使用 break
、return
或 的情况下完全退出 for 循环如果
?
最佳答案
我能想到的最好的是:
for (int i = 0; i < 10; i++)
{
i = (i == 5) ? 10 : i;
Trace.WriteLine("i = " + i.ToString());
}
...这将导致循环运行六次 (i=0..5) 并显示此...
i = 0
i = 1
i = 2
i = 3
i = 4
i = 10
“退出循环”(以一种特别讨厌的方式)的另一种方法是这样做......
for (int i = 0; i < 10; i++)
{
int a = 3 / ((i == 5) ? 0 : 1);
Trace.WriteLine("i = " + i.ToString());
}
..which crashes out, errr, successfully 退出循环而不使用break
, return
or if
命令。
i = 0
i = 1
i = 2
i = 3
i = 4
A first chance exception of type 'System.DivideByZeroException' occurred in MikesProgram.dll
language is C# .it was an interview question actually..curious
我得到这份工作了吗?
我需要检查您的健康和 dentry 计划,并且我必须在周四早点离开去学校接我的女儿。
;-)
关于c# - 退出循环而不中断/返回/如果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918970/