微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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?

原文地址:https://www.jb51.cc/csharp/97408.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐