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

标签 c# static-constructor

<分区>

假设我有 2 个类:

public abstract class Foo
{
    static Foo()
    {
        print("4");
    }
}

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

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

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

  1. Foo 的静态构造函数(再次假设第一次访问)> print 4
  2. Bar 的静态构造函数> print 2
  3. 执行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# - 为什么不调用我的基类中的静态构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20092211/

相关文章:

c# - 正则表达式匹配以逗号分隔的列表,末尾没有逗号

c# - 在 .NET 中逐个节点地比较两个 XML 文件

c# - .Net : Do static constructors get called when a constant is access?

.net-4.0 - 派生类的c++/cli静态构造函数未被调用

c# - 在引用任何静态成员之前调用静态构造函数

java - 抽象类中的静态构造函数?

c# - 使用 Visual Studio C# 调试器查找重新抛出的异常最初抛出的位置?

c# - 在 MVC 6 中将 View 渲染为字符串

c# - 添加自定义控件mvvm caliburn