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

前端之家收集整理的这篇文章主要介绍了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?

猜你在找的C#相关文章