C#在方法中初始化const变量

时间:2013-06-08 21:08:25

标签: c# methods const

如果类中的方法具有const变量,例如:

public void MyMethod()
{
   const int myVariable = 5;

   // blah
}

myVariable只会初始化一次(当我第一次调用该方法时)或每次调用该方法时?

2 个答案:

答案 0 :(得分:11)

都不是。决不。常量主要在编译时使用 。它不是变量也不是字段。任何使用常量(“ldc.i4.5”)的代码都将使用文字值5 - 但在运行时不需要常量本身。

答案 1 :(得分:3)

从不。会发生什么是编译器会将该变量刻录到方法中:好像它从未存在过,只需将值放在const的名称中。

e.g。

public double MyMethod()
{
    const int anInt = 45;
    return anInt * (1/2.0) + anInt;
}

将编译为:

public double MyMethod()
{
    return 45 * (1/2.0) + anInt; 
    //actually that would also be calculated at compile time,
    //but that's another implementation detail.
}