为什么 CLR 通过初始化优化掉未使用的静态字段?

Why CLR optimizing away unused static field with initialization?

让我们有两个代码片段:

答:

public class Foo
{
    private static Bar _unused = new Bar();
}

B:

public class Foo
{
    private static Bar _unused;

    static Foo()
    {
        _unused = new Bar();
    }
}

A 的情况下,CLR 甚至不会调用 Bar ctor(除非它是调试版本或附加了调试器),但是在 B[ 的情况下=37=] 在任何情况下都会被调用。

事情是,在 Bar 构造函数中,可以进行调用,使该实例可以从其他地方访问 - 最典型的是 events subscriptions.

所以:

  • 为什么案例 AB 的评估不同?
  • 为什么 CLR 在 A 的情况下根本不调用 Bar ctor - 因为它 在 ctor 完成并实例化之前,不应将其评估为垃圾 分配给适当的字段?

如果你don't create a constructor:

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

如果你do have a static constructor:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.