Contents

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

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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);
}
}
}
}

输出如下:

1
2
3
4
5
6
In static constructor
TypeInitializationException
TypeInitializationException
TypeInitializationException
TypeInitializationException
TypeInitializationException
Contents