在C#中初始化静态变量内联或静态构造函数的差异

Cur*_*rro 18 .net c# static constructor initialization

我想知道初始化内联静态成员有什么区别,如:

class Foo
{
    private static Bar bar_ = new Bar();
}
Run Code Online (Sandbox Code Playgroud)

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

class Foo
{
    static Foo()
    {
        bar_ = new Bar();
    }
    private static Bar bar_;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 17

如果类型中有静态构造函数,则由于不再应用beforefieldinit标志而导致类型初始化.

它还影响初始化顺序 - 变量初始化程序都在静态构造函数之前执行.

据我所知,这就是它.

  • 有关其重要性的具体示例:http://stackoverflow.com/questions/217932/whats-the-difference-in-these-ways-of-creating-the-static-instance-for-a-single#218005 (3认同)