似乎取决于代码行的顺序。以下代码可以正常工作:
static private List<int> a = new List<int>() { 1 };
static private List<int> b = new List<int>() { a[0] };
虽然这段代码无法工作(会抛出NullReferenceException
异常)
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { 1 };
显然,递归依赖关系没有规则。但有一个奇怪的现象是编译器并没有抱怨...
编辑 - 在"跨文件"情况下会发生什么?如果我们声明这两个类:
public class A {
public static List<int> a = new List<int>() { B.b[0] };
}
public class B {
public static List<int> b = new List<int>() { A.a[0] };
}
尝试使用以下代码访问它们:
try catch (Exception e)
try catch (Exception e)
try catch (Exception e)
我们得到了这个输出:
we are getting this output:
The type initializer for 'A' threw an exception.
Object reference not set to an instance of an object.
The type initializer for 'A' threw an exception.
因此,在静态构造函数 A
中初始化 B
导致异常,并使字段 a
保留了默认值(null)。由于 a
是 null
,b
也无法正确初始化。
如果我们没有循环依赖,一切都能正常工作。
编辑:以防您没有阅读评论,Jon Skeet 提供了一篇非常有趣的阅读材料:静态构造函数和类型初始化器之间的区别。