差异初始化静态变量inline或在C#中的静态构造函数 [英] Difference initializing static variable inline or in static constructor in C#

查看:176
本文介绍了差异初始化静态变量inline或在C#中的静态构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道初始化静态成员内联之间的区别在于:

I would like to know what is the difference between initializing a static member inline as in:

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

或在静态构造函数中初始化它,如下所示:

or initializing it inside the static constructor as in:

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


推荐答案

如果你有一个静态构造函数在您的类型中,由于 beforefieldinit 标记不再应用,它会更改类型初始化。

If you have a static constructor in your type, it alters type initialization due to the beforefieldinit flag no longer being applied.

它也影响初始化顺序 - 变量初始化器都在静态构造函数之前执行。

It also affects initialization order - variable initializers are all executed before the static constructor.

据我所知。

这篇关于差异初始化静态变量inline或在C#中的静态构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆