What's the best way to ensure a base class's static constructor is called?

前端 未结 6 1189
抹茶落季
抹茶落季 2020-12-02 16:51

The documentation on static constructors in C# says:

A static constructor is used to initialize any static data, or to perform a particular action

6条回答
  •  难免孤独
    2020-12-02 17:35

    In all of my testing, I was only able to get a call to a dummy member on the base to cause the base to call its static constructor as illustrated:

    class Base
    {
        static Base()
        {
            Console.WriteLine("Base static constructor called.");
        }
    
        internal static void Initialize() { }
    }
    
    class Derived : Base
    {
        static Derived()
        {
            Initialize(); //Removing this will cause the Base static constructor not to be executed.
            Console.WriteLine("Derived static constructor called.");
        }
    
        public static void DoStaticStuff()
        {
            Console.WriteLine("Doing static stuff.");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Derived.DoStaticStuff();
        }
    }
    

    The other option was including a static read-only member in the derived typed that did the following:

    private static readonly Base myBase = new Base();

    This however feels like a hack (although so does the dummy member) just to get the base static constructor to be called.

提交回复
热议问题