Avi*_*ner 8 c# static-constructor
可以说我有两节课:
public abstract class Foo
{
static Foo()
{
print("4");
}
}
public class Bar : Foo
{
static Bar()
{
print("2");
}
static void DoSomething()
{
/*...*/
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在调用之后Bar.DoSomething()(假设这是我第一次访问Bar类),事件的顺序将是:
42DoSomething在底线,我希望42打印出来.
经过测试,似乎只是2在打印.
这甚至都不是答案.
你能解释一下这种行为吗?
规范说明:
类的静态构造函数在给定的应用程序域中最多执行一次.静态构造函数的执行由应用程序域中发生的以下第一个事件触发:
- 创建了一个类的实例.
- 引用该类的任何静态成员.
因为您没有引用基类的任何成员,所以构造函数不会被驱逐.
试试这个:
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()
{
/*...*/
}
}
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息:
不调用基类静态构造函数的原因是因为,我们还没有访问基类的任何静态成员,也没有提到派生类的实例.
根据文档,这些是调用静态构造函数的时间.
在创建第一个实例或引用任何静态成员之前自动调用它.
在下面的代码中,当我们调用DoSomething基类时,将调用构造函数
public abstract class Foo
{
static Foo()
{
Console.Write("4");
j = 5;
}
protected static int j;
public static void DoNothing()
{
}
}
public class Bar : Foo
{
static Bar()
{
Console.Write("2");
}
public static void DoSomething()
{
Console.Write(j);
}
}
Run Code Online (Sandbox Code Playgroud)