stackoverflow上举了这个例子说明在C#中,如果static constructor只会被调用一次,即使抛了异常,也不会重试调用。如果抛了异常,那么在这个appdomain里面,这个类就不能用了。

示例代码:

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);
            }
        }
    }
}

输出如下:

In static constructor
TypeInitializationException
TypeInitializationException
TypeInitializationException
TypeInitializationException
TypeInitializationException

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2021-05-23
  • 2021-08-08
  • 2021-11-08
  • 2021-12-23
猜你喜欢
  • 2021-09-05
  • 2022-01-29
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
  • 2021-06-22
  • 2022-02-17
相关资源
相似解决方案