我个人使用while(true)
进行无限循环,但我看过使用for(;;)
的在线示例。实际上,这两者之间是否有任何差异,还是只是一种风格?
答案 0 :(得分:7)
没有区别。我查了一下IL。我写了两个函数如下。
class Program
{
static void Main(string[] args)
{
System.Console.ReadLine();
}
static void EndlessWhile()
{
while (true)
{
Console.WriteLine("Hello");
}
}
static void EndlessFor()
{
for (; ; )
{
Console.WriteLine("Hello");
}
}
}
// IL of both the functions are mentioned below.
.method private hidebysig static void EndlessWhile() cil managed
{
// Code size 20 (0x14)
.maxstack 1
.locals init ([0] bool CS$4$0000)
IL_0000: nop
IL_0001: br.s IL_0010
IL_0003: nop
IL_0004: ldstr "Hello"
IL_0009: call void [mscorlib]System.Console::WriteLine(string)
IL_000e: nop
IL_000f: nop
IL_0010: ldc.i4.1
IL_0011: stloc.0
IL_0012: br.s IL_0003
} // end of method Program::EndlessWhile
.method private hidebysig static void EndlessFor() cil managed
{
// Code size 20 (0x14)
.maxstack 1
.locals init ([0] bool CS$4$0000)
IL_0000: nop
IL_0001: br.s IL_0010
IL_0003: nop
IL_0004: ldstr "Hello"
IL_0009: call void [mscorlib]System.Console::WriteLine(string)
IL_000e: nop
IL_000f: nop
IL_0010: ldc.i4.1
IL_0011: stloc.0
IL_0012: br.s IL_0003
} // end of method Program::EndlessFor
答案 1 :(得分:1)
可能只是风格。
我依旧记得过去有一个C ++编译器给我一个警告while(true)
而不是for(;;)
这可能是最初风格的来源。
答案 2 :(得分:1)
他们生成相同的IL,所以选择你喜欢的任何东西。虽然说无限循环通常不是无穷无尽的,所以你可能想要将退出条件表达为循环的一部分。