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

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

问题描述

我想知道什么是内联初始化静态成员中的区别:

 类Foo
{
    私有静态酒吧bar_ =新的酒吧();
}
 

或静态构造函数中对其进行初始化,如下所示:

 类Foo
{
    静态的Foo()
    {
        bar_ =新的酒吧();
    }
    私有静态酒吧bar_;
}
 

解决方案

如果你有一个静态构造函数在你的类型,它改变类型初始化由于的 beforefieldinit 标志不再适用。

这也影响初始化顺序 - 变量初始化都是静态构造函数之前的所有执行

这就是它,据我所知,虽然。

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_;
}

解决方案

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.

That's about it as far as I know though.

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

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