【问题标题】:Derived.<static variable from Base> doesn't invoke derived's static constructorDerived.<static variable from Base> 不调用派生的静态构造函数
【发布时间】:2017-08-01 08:54:07
【问题描述】:

为什么下面代码中没有调用 Derived 中的静态构造函数?

class Base
{
    public static Base Instance;
    static Base() { Console.WriteLine("Static Base invoked."); }
}

class Derived : Base
{
    static Derived() { 
        Instance = new Derived();
        Console.WriteLine("Static Derived invoked."); 
    }
}

void Main()
{
    var instance = Derived.Instance;
}

OUTPUT:
Static Base invoked.

【问题讨论】:

    标签: c# constructor static


    【解决方案1】:

    这是因为通过派生类访问基类的静态成员实际上被编译为通过基类,即声明该成员的基类。

    因此,这个:

    Derived.Instance
    

    其实是这样编译的:

    Base.Instance
    

    因此没有代码触及Derived,这就是它的静态构造函数没有被调用的原因。

    这是您的 Main 方法的编译方式(发布):

    IL_0000:  ldsfld      Base.Instance
    IL_0005:  pop
    IL_0006:  ret 
    

    【讨论】:

    • 我无法在 C# 规范中找到正确的段落。我很确定它就在那里,但我似乎找不到合适的词组来搜索。
    猜你喜欢
    • 2015-06-12
    • 2011-09-17
    • 2022-12-03
    • 1970-01-01
    • 2018-07-21
    • 2012-11-06
    • 2020-11-28
    • 2016-07-19
    • 2019-02-01
    相关资源
    最近更新 更多