C# 为什么不是';我的基类中的静态构造函数调用了吗?
假设我有两门课:C# 为什么不是';我的基类中的静态构造函数调用了吗?,c#,static-constructor,C#,Static Constructor,假设我有两门课: public abstract class Foo { static Foo() { print("4"); } } public class Bar : Foo { static Bar() { print("2"); } static void DoSomething() { /*...*/ } } 我希望在调用Bar.DoSomething()(假
public abstract class Foo
{
static Foo()
{
print("4");
}
}
public class Bar : Foo
{
static Bar()
{
print("2");
}
static void DoSomething()
{
/*...*/
}
}
我希望在调用Bar.DoSomething()
(假设这是我第一次访问Bar类)之后,事件的顺序是:
4
2
DoSomething
42
。测试后,似乎只打印了
2
。你能解释一下这种行为吗?基类静态构造函数没有被调用的原因是,我们还没有访问基类的任何静态成员,也没有访问派生类的实例 根据文档,这些是调用静态构造函数的时间 它在创建第一个实例或任何其他实例之前自动调用 静态成员被引用 在下面的代码中,当我们调用
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);
}
}
该规范规定: 类的静态构造函数在给定的应用程序域中最多执行一次。静态构造函数的执行由应用程序域中发生的以下第一个事件触发:
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()
{
/*...*/
}
}
有关更多信息: