加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:03:42 所属栏目:百科 来源:网络整理
导读:参见英文答案 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 DoSome
参见英文答案 > 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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读