静态只读VS常量 - 不同的组件POV? [英] Static readonly vs const — different assemblies POV?
问题描述
有关于这个主题的许多问题,但没有(除了之一,但仍然是一个缺一< 。/ A>)正在处理以下情形
There are many questions about this subject , but none (except one but still a short one) are dealing with the following scenario.
这是C#4本书:
马克还写道:
如果你改变一个常量的值,则需要重建所有的
客户
if you change the value of a const, you need to rebuild all the clients
问:
1),这是为什么?都是静态只读
和常量
- 静态
1) Why is that? Are both static readonly
and const
— static
?
2)的其中,的实际值保存?
2) Where actually the values are saved ?
3)如何制作字段静态只读
实际上解决
这个问题?
3) How does making a field static readonly
actually solve
this problem "behind the scene" ?
推荐答案
没有,一个const是一个常量,不是一个静态的 - 这是一个特殊的情况下,不同的规则;它的仅设置在编译时(而不是运行时),它的处理方式不同。
no, a const is a const, not a static - it is a special-case, with different rules; it is only set at compile-time (not runtime), and it is handled differently
这里的关键是以下方法:
the crux here is what the following means:
var foo = SomeType.StaticValue;
VS
vs
var bar = SomeType.ConstValue;
在第一个的情况下,从<$读取在运行时的值C $ C> SOMETYPE ,即通过一个 ldsfld
;然而,在第二种情况下,被编译的的值,也就是说,如果 ConstValue
恰好是 123
,那么第二个就是相同为:
in the first case, it reads the value at runtime from SomeType
, i.e. via a ldsfld
; however, in the second case, that is compiled to the value, i.e. if ConstValue
happens to be 123
, then the second is identical to:
var bar = 123;
在运行时,它是从哪里来的事实 SOMETYPE
不存在,作为值( 123
)进行了评估由编译器,然后保存。因此,它需要一个重新拾起新值。
at runtime, the fact that it came from SomeType
does not exist, as the value (123
) was evaluated by the compiler, and stored. Hence it needs a rebuild to pick up new values.
更改为静态只读
表示加载值从 SOMETYPE
被保留
Changing to static readonly
means that the "load the value from SomeType
" is preserved.
所以以下内容:
static int Foo()
{
return Test.Foo;
}
static int Bar()
{
return Test.Bar;
}
...
static class Test
{
public static readonly int Foo = 123;
public const int Bar = 456;
}
编译如下:
compiles as:
.method private hidebysig static int32 Bar() cil managed
{
.maxstack 8
L_0000: ldc.i4 0x1c8
L_0005: ret
}
.method private hidebysig static int32 Foo() cil managed
{
.maxstack 8
L_0000: ldsfld int32 ConsoleApplication2.Test::Foo
L_0005: ret
}
请注意,在酒吧
的 LDC
加载值直接(0x1c8 == 456),与<$ C $ 。C>测试完全消失了。
Note that in the Bar
, the ldc
is loading a value directly (0x1c8 == 456), with Test
completely gone.
有关完整的常量的是的使用静态字段,但是实现 - 它是的文字的领域,这意味着:在编译器进行评估,而不是在运行时
For completeness, the const is implemented with a static field, but - it is a literal field, meaning: evaluated at the compiler, not at runtime.
.field public static literal int32 Bar = int32(0x1c8)
.field public static initonly int32 Foo
这篇关于静态只读VS常量 - 不同的组件POV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!