我在程序集中有以下代码:
public class Class1
{
public const int x = 10;
}
在不同的程序集中,我有:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Class1.x);
Console.ReadKey();
}
}
当然输出是
10
,但是后来我将x
更改为20
:public class Class1
{
public const int x = 20;
}
我重新编译了程序集,并将其移至命令行程序的bin目录。但是,在编译包含
10
函数的程序集之前,程序的输出仍然是main
。为什么会这样呢?
最佳答案
C#中的常数值在使用它们的位置处内联。 IE。第Console.WriteLine(Class1.x);
行将编译为Console.WriteLine(10);
。生成的IL代码如下所示:
.entrypoint
.maxstack 8
IL_0000: nop
IL_0001: ldc.i4.s 10 // here just integer value 10 is loaded on stack
IL_0003: call void [mscorlib]System.Console::WriteLine(int32)
不会有任何指向Class1的链接。因此,在重新编译
Main
程序集之前,它将具有内联值10
。 MSDN对此常量使用情况发出警告:他们提到常量表达式仅在编译时评估。 IE。
Class1.x
将在Main
汇编编译时进行评估,以获取10
的值。如果不重新编译,该值(value)将不会改变。但是不幸的是,它并没有清楚地解释这种行为的原因(至少对我而言)。BTW Named and Optional parameters值也内联在调用方法的位置,并且您还需要重新编译调用程序程序集以更新值。