Why isn't the static constructor from my base class called? [duplicate]

风格不统一 提交于 2019-12-10 03:12:27

问题


Lets say I have 2 classes:

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

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

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

I expected that after calling Bar.DoSomething() (assuming this is the first time I access the Bar class) the order of event will be:

  1. Foo's static constructor (again, assuming first access) > print 4
  2. Bar's static constructor > print 2
  3. Execution of DoSomething

At the bottom line I expect 42 to be printed.
After testing, it seems that only 2 is being printed.
And that is not even an answer.

Can you explain this behavior?


回答1:


The specification states:

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.

Because you are not referencing any of the members of the base class, the constructor is not being excecuted.

Try this:

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()
    {
        /*...*/
    }
}

For more information:

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



回答2:


The reason base class static constructor is not called is because, we are not yet accessing any static members of the base class nor cereating the instance of the derived class.

As per documentation these are the times when a static constructor will be called.

It is called automatically before the first instance is created or any static members are referenced.

In the below code when we invoke DoSomething the base class constructor will be called

   public abstract class Foo
    {
        static Foo()
        {
            Console.Write("4");
            j = 5;
        }

        protected static int j;

        public static void DoNothing()
        {

        }
    }

    public class Bar : Foo
    {
        static Bar()
        {
            Console.Write("2");
        }

        public static void DoSomething()
        {
            Console.Write(j);
        }
    }


来源:https://stackoverflow.com/questions/20092211/why-isnt-the-static-constructor-from-my-base-class-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!