一千萬個為什麽

搜索

C#兩個類,靜態成員互相引用


我想知道為什麽這段代碼不會以無休止的遞歸結束。我想這與靜態成員自動初始化為默認值有關,但有人可以告訴我“一步一步”'a'如何得到2的值和'b'為1?

public class A
{
    public static int a = B.b + 1;
}
public class B
{
    public static int b = A.a + 1;
}

static void Main(string[] args)
{
    Console.WriteLine("A.a={0}, B.b={1}", A.a, B.b); //A.a=2, B.b=1
    Console.Read();
}

最佳答案

我想:

  • A.a is queried, which causes the A static initializer to fire
  • This accesses B.b, causing the B static initializer to fire
  • A.a is queried; the type initializer is already activated (but no assignment has yet occurred), so the field (not yet assigned) is read as 0
  • 0 + 1 is 1, which is assigned to B.b <===========================
  • we now exit the B cctor and go back to the A cctor
  • 1 + 1 is 2, which is assigned to A.a <===========================
  • we now exit the A cctor
  • 2 is returned (WriteLine) for A.a
  • we query (on WriteLine) B.b; the cctor has already fired so we see 1

轉載註明原文: C#兩個類,靜態成員互相引用

猜你喜歡