静态只读字段在内存中是否只有一个副本?

Does a static readonly field have only a single copy in memory?

无论存在多少个封装类型的对象,静态只读字段在内存中是否只有一个副本?

例如:

class A{
  static readonly SomeType foo;
  static A(){
    foo = new SomeType();
  }
...

那么foo是不是在整个程序中只存在一次,不管A有多少个实例?

来自 ECMA-335(强调我的)

I.8.4.3 Static fields and static methods

Types can declare locations that are associated with the type rather than any particular value of the type. Such locations are static fields of the type. As such, static fields declare a location that is shared by all values of the type. Just like non-static (instance) fields, a static field is typed and that type never changes. Static fields are always restricted to a single application domain basis (see § I.12.5 ), but they can also be allocated on a per-thread basis.

ThreadStaticAttribute 允许在每个线程的基础上进行静态分配。

对于大多数常见用途,您的代码段中只有一个 foo 引用的 SomeType 实例。

如果涉及多个应用域,或者用[ThreadStatic]修饰,那么可能存在多个实例。