重新编译参考程序集时常量值不变 [英] Constant value not changing when recompiling referenced assembly

查看:127
本文介绍了重新编译参考程序集时常量值不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在汇编中有以下代码:

I have this code in an assembly:

public class Class1
{
    public const int x = 10;
}

在一个不同程序集中,我有: / p>

and in a different assembly I have:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Class1.x);
        Console.ReadKey();
    }
}

当然,输出是 10 ,但后来我将 x 更改为 20

Of course the output was 10, but then I changed x to 20:

public class Class1
{
    public const int x = 20;
}

我重新编译了程序集并将其移至命令行程序的bin目录。但是,在我编译包含 main 函数的程序集之前,我的程序的输出仍然为 10

I recompiled the assembly and moved it to my command line program's bin directory. However, the output of my program was still 10, until I compiled assembly containing the main function.

为什么会这样?

推荐答案

C#中的常量值是内联的使用它们的地方。即行 Console.WriteLine(Class1.x); 将被编译为 Console.WriteLine(10); 。生成的IL代码如下所示:

Constants values in C# are in-lined in place where they are used. I.e. line Console.WriteLine(Class1.x); will be compiled to Console.WriteLine(10);. Generated IL-code will look like:

  .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 对此常量使用情况发出警告:

There will not be any link to Class1. So, until you re-compile Main assembly, it will have in-lined value 10. MSDN has warning about this case of constants usage:


不要创建常量来表示您希望
随时更改的信息。例如,请勿使用常量字段存储
的价格,公司的产品版本号或品牌名称。这些值会随着时间变化,并且由于编译器
会传播常量,因此使用您的库编译的其他代码将需要重新编译
才能查看更改。

Don’t create a constant to represent information that you expect to change at any time. For example, don’t use a constant field to store the price of a service, a product version number, or the brand name of a company. These values can change over time, and because compilers propagate constants, other code compiled with your libraries will have to be recompiled to see the changes.

他们提到常量表达式仅在编译时求值。即 Class1.x 将在 Main 程序集编译时间评估为 10 。如果不重新编译,该价值将不会改变。但是不幸的是,它并不能清楚地解释这种行为的原因(至少对我而言)。

They mention that constant expressions are evaluated only at compile time. I.e. Class1.x will be evaluated at Main assembly compile time to value 10. And without re-compilation that value will not change. But unfortunately it does not clearly explains reason of such behavior (to me at least).

BTW 命名和可选参数值也被内联在调用方法的位置,并且您还需要重新编译调用程序程序集以更新值。

BTW Named and Optional parameters values are also in-lined in place where method is called, and you also need to re-compile caller assembly to update values.

这篇关于重新编译参考程序集时常量值不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆