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

标签 c# .net optimization initialization static-members

让我们有两个代码片段:

答:

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

乙:

public class Foo
{
    private static Bar _unused;

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

A 的情况下,CLR 甚至不会调用 Bar ctor(除非它是调试版本或附加了调试器),但是在 B 的情况下,它会在下面调用所有情况。

问题在于,在 Bar 构造函数中,可以进行调用,使该实例可以从其他地方访问 - 最典型的是事件订阅

所以:

  • 为什么案例 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.

关于c# - 为什么 CLR 通过初始化优化掉未使用的静态字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32885626/

相关文章:

c# - 函数的别名

c++ - 给另一个 vector 内存的 std::vector 所有权?

oracle - Azure 数据工厂查找事件查询错误操作已超时

c# - 当通用决策基于数据库值时,如何使用 C# 泛型来实现此实现

c# - ASP.NET 背景图片

.net - 为什么我不能编辑我的 DataGridView 中的值,即使它没有设置为只读?

c# - 在后面的代码中,我如何使验证器不验证?

c# - 将 app.config 作为 MSBuild 脚本的一部分进行更改

c++ - 使用指针的低位作为标志的可移植性如何?

c# - 将非常大的二进制文件逐步转换为 Base64String