c# - 退出循环而不中断/返回/如果

标签 c# return break

如果你有一个for循环:

for(i=0;i<10;i++){} 

现在,当 i==5 时,如何在不使用 breakreturn 的情况下完全退出 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/

相关文章:

c# - 从另一个 View 返回数据 Xamarin.iOS

C# 在基类中创建派生类的实例

c - 为什么 main() 不需要返回类型(比如 int),即使它返回一个整数?

c - 如何跳出嵌套循环?

linux - 我不明白 break 命令

c# - 正则表达式字符串定义问题

python - 从python中的for循环返回值

python - 如何从power bi中的python函数返回单个数据帧

r - 在条件内停止执行脚本

c# - 如何在C#、A909中获取41104的ushort数据?