ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-06-11 21:52:54  阅读:176  来源: 互联网

标签:c optimization net initialization static-members


我们有两个代码片段:

A:

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中它在所有情况下都被调用.

问题是,在Bar构造函数中,可以进行调用,使其可以从其他地方访问 – 最常见的是事件订阅.

所以:

>为什么案例A和B的评估方式不同?
>为什么CLR根本没有调用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,optimization,net,initialization,static-members
来源: https://codeday.me/bug/20190611/1221527.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有