本文介绍了静态只读VS常量 - 不同的组件POV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 有关于这个主题的许多问题,但没有(除了之一,但仍然是一个缺一)正在处理以下情形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; VSvsvar bar = SomeType.ConstValue; 在第一个的情况下,从 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),与测试完全消失了。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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!