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

前端 未结 6 1175
抹茶落季
抹茶落季 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:27

    The rules here are very complex, and between CLR 2.0 and CLR 4.0 they actually changed in subtle and interesting ways, that IMO make most "clever" approaches brittle between CLR versions. An Initialize() method also might not do the job in CLR 4.0 if it doesn't touch the fields.

    I would look for an alternative design, or perhaps use regular lazy initialization in your type (i.e. check a bit or a reference (against null) to see if it has been done).

    0 讨论(0)
  • 2020-12-02 17:28

    I almost alway regret relying on something like this. Static methods and classes can limit you later on. If you wanted to code some special behavior for your Type class later you would be boxed in.

    So here is a slight variation on your approach. It is a bit more code but it will allow you to have a custom Type defined later that lets you do custom things.

        abstract class TypeBase
        {
            private static bool _initialized;
    
            protected static void Initialize()
            {
                if (!_initialized)
                {
                    Type<int>.Instance = new Type<int> {Name = "int"};
                    Type<long>.Instance = new Type<long> {Name = "long"};
                    Type<double>.Instance = new Type<double> {Name = "double"};
                    _initialized = true;
                }
            }
        }
    
        class Type<T> : TypeBase
        {
            private static Type<T> _instance;
    
            public static Type<T> Instance
            {
                get
                {
                    Initialize();
                    return _instance;
                }
                internal set { _instance = value; }
            }
    
            public string Name { get; internal set; }
        }
    

    Then later when you get to adding a virtual method to Type and want a special implementation for Type you can implement thus:

    class TypeInt : Type<int>
    {
        public override string Foo()
        {
            return "Int Fooooo";
        }
    }
    

    And then hook it up by changing

    protected static void Initialize()
    {
          if (!_initialized)
          {
              Type<int>.Instance = new TypeInt {Name = "int"};
              Type<long>.Instance = new Type<long> {Name = "long"};
              Type<double>.Instance = new Type<double> {Name = "double"};
              _initialized = true;
           }
    }
    

    My advice would be to avoid static constructors - it is easy to do. Also avoid static classes and where possible static members. I am not saying never, just sparingly. Prefer a singleton of a class to a static.

    0 讨论(0)
  • 2020-12-02 17:31

    Just an idea, you can do something like this:

        abstract class TypeBase
        {
            static TypeBase()
            {
                Type<int>.Name = "int";
                Type<long>.Name = "long";
                Type<double>.Name = "double";
            }
        }
    
        class Type<T> : TypeBase
        {
            static Type() 
            {
                new Type<object>();
            }
    
            public static string Name { get; internal set; }
        }
    
        class Program
        {
            Console.WriteLine(Type<int>.Name);
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 17:42

    You may call static constructor explicity, so you will not have to create any methods for initialization:

    System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof (TypeBase).TypeHandle);
    

    You may call it in static constructor of derived class.

    0 讨论(0)
  • 2020-12-02 17:43

    As others have noted, your analysis is correct. The spec is implemented quite literally here; since no member of the base class has been invoked and no instance has been created, the static constructor of the base class is not called. I can see how that might be surprising, but it is a strict and correct implementation of the spec.

    I don't have any advice for you other than "if it hurts when you do that, don't do that." I just wanted to point out that the opposite case can also bite you:

    class Program 
    {
      static void Main(string[] args)
      {      
        D.M();
      }      
    
    }
    class B 
    { 
      static B() { Console.WriteLine("B"); }
      public static void M() {}
    } 
    class D: B 
    { 
      static D() { Console.WriteLine("D"); }
    }
    

    This prints "B" despite the fact that "a member of D" has been invoked. M is a member of D solely by inheritance; the CLR has no way of distinguishing whether B.M was invoked "through D" or "through B".

    0 讨论(0)
提交回复
热议问题