Exception in static constructor

前端 未结 3 415
无人共我
无人共我 2020-12-28 12:27

I\'ve dug around SO for an answer to this, and the best one I can find so far is here, however that is geared toward instances with static constructors; I\'m only using the

相关标签:
3条回答
  • 2020-12-28 13:20

    From MSDN:

    If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

    0 讨论(0)
  • 2020-12-28 13:22

    The other two answers are good answers to your direct question - here's a metaanswer - you should be throwing the exception in the method when you detect that the configuration elements are not populated, rather than in the constructor. IMHO, "not configured" is a valid configuration state for those elements at the constructor phase, just not at SendMail time. That will sidestep this whole problem.

    0 讨论(0)
  • 2020-12-28 13:24

    Once a type initializer has failed once, it is never retried. The type is dead for the lifetime of the AppDomain. (Note that this is true for all type initializers, not just for types with static constructors. A type with static variables with initializer expressions, but no static constructors, can exhibit subtle differences in the timing of the type initializer execution - but it'll still only happen once.)

    Demonstration:

    using System;
    
    public sealed class Bang
    {
        static Bang()
        {
            Console.WriteLine("In static constructor");
            throw new Exception("Bang!");
        }
    
        public static void Foo() {}
    }
    
    class Test
    {
        static void Main()
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    Bang.Foo();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.GetType().Name);
                }
            }
        }
    }
    

    Output:

    In static constructor
    TypeInitializationException
    TypeInitializationException
    TypeInitializationException
    TypeInitializationException
    TypeInitializationException
    

    As you can see, the static constructor is only called once.

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