【问题标题】:Why the order of entering static .ctors is different from instance .ctors in inherited classes?为什么在继承类中输入静态 .ctors 的顺序与实例 .ctors 不同?
【发布时间】:2012-02-04 13:05:08
【问题描述】:

为什么 var b = new B() 首先进入 static B() .ctor 而不是 static A() .ctor 而不是像实例构造函数那样反之(@ 987654326@public B())?

public class A
{
    static A() {}
    public A() {}
}

public class B : A
{
    static B() {}
    public B() {}
}

【问题讨论】:

标签: c# .net c#-4.0 constructor static-constructor


【解决方案1】:

从技术上讲,首先输入B 的实例构造函数。但它做的第一件事是调用A 的构造函数,然后才转到用户定义的主体。

所以我假设直接在B的构造函数进入之前B的静态构造函数需要运行。

然后B的构造函数调用A的构造函数,触发A的静态构造函数。

【讨论】:

  • 语言规范中详细说明了静态构造函数的规则。具体来说,静态构造函数在“创建类类型的实例 [或] 引用类类型的任何静态成员”时运行。请注意,“引用了派生类型的静态成员”不在列表中。
猜你喜欢
  • 1970-01-01
  • 2016-10-01
  • 2010-10-20
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-23
相关资源
最近更新 更多