假设我有 2 个类:
public abstract class Foo
{
static Foo()
{
print("4");
}
}
public class Bar : Foo
{
static Bar()
{
print("2");
}
static void DoSomething()
{
/*...*/
}
}
我预计在调用 Bar.DoSomething()
之后(假设这是我第一次访问 Bar 类)事件的顺序将是:
- Foo 的静态构造函数(再次假设第一次访问)> print
4
- Bar 的静态构造函数> print
2
- 执行
DoSomething
在最后一行,我希望打印 42
。
经过测试,好像只有2
被打印出来了。
And that is not even an answer .
你能解释一下这种行为吗?
规范指出:
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
- An instance of the class is created.
- Any of the static members of the class are referenced.
因为您没有引用基类的任何成员,所以构造函数没有被执行。
试试这个:
public abstract class Foo
{
static Foo()
{
Console.Write("4");
}
protected internal static void Baz()
{
// I don't do anything but am called in inherited classes'
// constructors to call the Foo constructor
}
}
public class Bar : Foo
{
static Bar()
{
Foo.Baz();
Console.Write("2");
}
public static void DoSomething()
{
/*...*/
}
}
更多信息: