【问题标题】:What are the practical differences between while(true) and for(;;)?while(true) 和 for(;;) 之间的实际区别是什么?
【发布时间】:2010-09-09 09:42:23
【问题描述】:

我个人将while(true) 用于无限循环,但我在网上看到过使用for(;;) 的示例。实际上,两者之间有什么区别,还是只是风格上的东西?

【问题讨论】:

标签: c# loops for-loop while-loop


【解决方案1】:

没有区别。我检查了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

【讨论】:

    【解决方案2】:

    它们生成相同的 IL,因此请选择您喜欢的任何内容。毕竟,无限循环通常不是无限的,因此您可能希望将退出条件表示为循环的一部分。

    【讨论】:

    • 我写的无限循环是一个运行在单独线程上的测试方法,每秒引发一个事件。它模拟了一个每秒发送一次更新的服务器。
    • @DanielT:我猜你依赖于线程被中止。你也可以让线程优雅地退出。
    【解决方案3】:

    可能只是风格。

    我隐约记得过去有一个 C++ 编译器给我一个警告 while(true) 而不是 for(;;)

    这可能是样式最初的来源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2021-06-12
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2010-10-22
      • 2012-05-08
      • 2011-03-06
      相关资源
      最近更新 更多