在.NET中,为什么常在编译时,而不是在JIT时进行评估? [英] In .NET, why are constants evaluated at compile time rather than at JIT time?

查看:125
本文介绍了在.NET中,为什么常在编译时,而不是在JIT时进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点惊讶的今天,当我在一个静态类改变一个公开可见的常量的值,然后更换组件的旧副本与新编译版本。令人惊讶的是,所引用的程序集现有的程序没有拿起不断的新的价值。也就是说,我没有重新编译的可执行文件,而是刚刚更换一个组件。

I got a bit of a surprise today when I changed the value of a publicly-visible constant in a static class and then replaced an old copy of the assembly with the newly-compiled version. The surprise was that the existing program that referenced the assembly didn't pick up the new value of the constant. That is, I didn't re-compile the executable but rather just replaced that one assembly.

我的实验的完整描述是如何常量是一个恒定的?

A full description of my experiment is at How constant is a constant?

我会承认自己是按这种行为感到非常惊讶。我明白这是怎么回事,但我不明白的为什么的。是否有一个具体的技术原因常量不能拾起在JIT的时间而不是编译时间?有没有情况下,这样做会打破东西?

I'll admit to being very surprised by this behavior. I understand what's going on, but I don't understand why. Is there a particular technical reason why constants couldn't be picked up at JIT time rather than compile time? Are there cases where doing that would break things?

推荐答案

常量应该是的。对于所有时间的。常量是像圆周率的值,或质子的铅原子的数目。

Constants are supposed to be constant. For all time. Constants are things like the value of pi, or the number of protons in a lead atom.

如果你不断的变化,这是不是一个真正的恒;使用一个只读字段来代替。

If your constant changes, it wasn't really a constant; use a readonly field instead.

另请参阅框架设计指南,其中规定:

Also see the Framework Design Guidelines, which state:

使用常数字段常量永远不会改变。编译器燃烧常量字段的值将直接调用code。因此常量值可以从来不破坏兼容性的风险而改变。

Use constant fields for constants that will never change. The compiler burns the values of const fields directly into calling code. Therefore const values can never be changed without the risk of breaking compatibility.

从本质上讲,变化,不需要重新编译一切都依赖于它的恒定是每一位打破的改变方法的签名而无需重新编译一切都依赖于它。编译器烘烤的各种关于有关从引用的程序集的元数据信息的假设时,它编译的依赖程序集。如果您的任意的变化,你不能指望的东西简单地继续工作。

Essentially, changing a constant without recompiling everything that depends on it is every bit as broken as changing the signature of a method without recompiling everything that depends on it. The compiler "bakes in" all kinds of assumptions about information about metadata from referenced assemblies when it compiles a dependent assembly. If you make any change, you cannot expect things to simply keep on working.

这篇关于在.NET中,为什么常在编译时,而不是在JIT时进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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