代码之家  ›  专栏  ›  技术社区  ›  pencilCake

在C#的局部范围中声明常量有什么好处吗?

  •  7
  • pencilCake  · 技术社区  · 14 年前

    谢谢,

    7 回复  |  直到 13 年前
        1
  •  5
  •   Spooks    14 年前

    在整个解决方案中通常使用常量。但是在本地范围中使用的好处是,您知道范围中的其他地方您不会更改它。另外,如果其他人正在处理这个代码,他们也会知道不要更改它。

        2
  •  5
  •   John Warlow    14 年前

    声明变量const还将允许编译器进行优化-而不是说在堆栈上分配一个int并将其值放在那里,编译器可以直接在代码中使用该值

    即:

    const int test = 4;
    DoSomething(test);
    

    DoSomething(4);
    

    由编译器

    编辑: 回复“常量传播”,因为注释框有大小限制

    代码

    int test = 4;
    Console.WriteLine(test*2);
    

    编译到

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       11 (0xb)
      .maxstack  2
      .locals init ([0] int32 test)
      IL_0000:  ldc.i4.4
      IL_0001:  stloc.0
      IL_0002:  ldloc.0
      IL_0003:  ldc.i4.2
      IL_0004:  mul
      IL_0005:  call       void [mscorlib]System.Console::WriteLine(int32)
      IL_000a:  ret
    } // end of method Program::Main
    

    const int test = 4;
    Console.WriteLine(test*2);
    

    优化到

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       7 (0x7)
      .maxstack  8
      IL_0000:  ldc.i4.8
      IL_0001:  call       void [mscorlib]System.Console::WriteLine(int32)
      IL_0006:  ret
    } // end of method Program::Main
    

    这是使用2010年发布的优化。

    我做了一个搜索来了解关于常量传播的更多信息,虽然可能,但是当前的编译器并没有像前面提到的那样做 here

        3
  •  3
  •   user151323 user151323    14 年前

        4
  •  3
  •   Dan Bryant    14 年前

    当我将布尔标志指示器传递给方法时,我喜欢这样做:

    const bool includeFoo = true;
    int result = bar.Compute(10, includeFoo);
    

        5
  •  2
  •   Jake Pearson    14 年前

    将local声明为const将让编译器知道您的意图,这样就不能在函数的其他地方更改变量的值。

        6
  •  1
  •   Paul Hadfield    14 年前

        7
  •  0
  •   abatishchev Karl Johan    14 年前

    取决于使用情况。。

    例如,

    void Foo()
    {
        const string xpath = "//pattern/node";
    
        new XmlDocument().SelectNodes(xpath);
    }
    

    在这种情况下,我认为const声明没有意义