重新编译参考程序集时常量值不变

编程入门 行业动态 更新时间:2024-10-21 23:03:14
本文介绍了重新编译参考程序集时常量值不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在汇编中有以下代码:

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.

更多推荐

重新编译参考程序集时常量值不变

本文发布于:2023-11-07 11:08:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:量值   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!