重新编译引用的程序集时常量值不会改变 [英] Constant value not changing when recompiling referenced assembly

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

问题描述

我在一个程序集中有这个代码:

I have this code in an assembly:

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

在一个不同的程序集中我有:

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 目录中.但是,我的程序的输出仍然是 10,直到我编译了包含 main 函数的程序集.

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# 中的常量值在使用它们的地方内联.IE.行 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.

他们提到常量表达式只在编译时计算.IE.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 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天全站免登陆