Why aren't all the static constructors called in C # (i.e. those from the parent classes)?

I have three classes Base, Derivedand Final. Derivedcomes from Baseand Finalcomes from Derived. All three classes have a static constructor. A class Derivedas an open static method called Setup. When I call Final.Setup, I expect all three static constructors to be executed, but only one of them starts Derived.

Here is a sample source code:

    abstract class Base
    {
        static Base()
        {
            System.Console.WriteLine ("Base");
        }
    }

    abstract class Derived : Base
    {
        static Derived()
        {
            System.Console.WriteLine ("Derived");
        }

        public static void Setup()
        {
            System.Console.WriteLine ("Setup");
        }
    }

    sealed class Final : Derived
    {
        static Final()
        {
            System.Console.WriteLine ("Final");
        }
    }

. , Final.Setup() Derived.Setup(), Final . Base ?

, no-operation Base Base. : - ?

+5
3

, ( TCPL):

  • .
  • .

Main, : , Main.

, , . (cctor).


: , , Base cctor , Base , .. Base.Initialize(), .

, , # ( Java ): , , ( cctor, ).

+5

, . , Final.Setup, - Derived.Setup, Final , . - , .

+1

C # rules specify that static constructors are called before the first instance of the class is created or any static member is affected, ergo may never, as in your case.

0
source

All Articles