行の順番にもよるようです。このコードは機能します:
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 };
したがって、明らかに循環依存のルールは存在しません。ただし、コンパイラが文句を言わないのは独特です...
編集 - 「ファイル全体」で何が起こっていますか? これら 2 つのクラスを宣言すると、次のようになります。
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 { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }
try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
次の出力が得られます。
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.
そのため、の初期化B
により、静的コンストラクターで例外が発生し、デフォルト値 (null) のA
lefts フィールドが発生します。ですa
ので、正常に初期化することもできません。a
null
b
周期的な依存関係がなければ、すべてうまくいきます。
編集: コメントを読んでいない場合に備えて、Jon Skeetは非常に興味深い読み物を提供しています:静的コンストラクターと型初期化子の違い。