c# – 为什么不调用我的基类的静态构造函数?

参见英文答案 > What’s the best way to ensure a base class’s static constructor is called?6个
可以说我有两节课:
public abstract class Foo
{
    static Foo()
    {
        print("4");
    }
}

public class Bar : Foo
{
    static Bar()
    {
        print("2");
    }

    static void DoSomething()
    {
        /*...*/
    }
}

我预计在调用Bar.DoSomething()之后(假设这是我第一次访问Bar类),事件的顺序将是:

> Foo的静态构造函数(再次,假设首次访问)>打印4
> Bar的静态构造函数>打印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:

  1. An instance of the class is created.
  2. 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()
    {
        /*...*/
    }
}

欲获得更多信息:

> C# in Depth – Jon Skeet: C# and beforefieldinit
> StackOverflow: What’s the best way to ensure a base class’s static constructor is called?

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...