public class A
{
public static int x;
static A()
{
x = B.y + 1;
Console.WriteLine("AAA");
}
}
class B
{
public static int y;
static B()
{
y = A.x + 1;
Console.WriteLine("BBB");
}
static void Main(string[] args)
{
Console.WriteLine("x={0},y={1}", A.x, B.y);
} }
该程序执行结果为:
AAA
BBB
X=1,Y=2;
想请问一下这个程序是怎样的顺序执行得出以上结果的?
{
public static int x;
static A()
{
x = B.y + 1;
Console.WriteLine("AAA");
}
}
class B
{
public static int y;
static B()
{
y = A.x + 1;
Console.WriteLine("BBB");
}
static void Main(string[] args)
{
Console.WriteLine("x={0},y={1}", A.x, B.y);
} }
该程序执行结果为:
AAA
BBB
X=1,Y=2;
想请问一下这个程序是怎样的顺序执行得出以上结果的?
1、进入static B
2、执行y = A.x + 1;
3、进入static A
4、执行x = B.y + 1
这时static B已经在第一步调用,所以不会重复调用,直接访问B.y,这时是0,所以结果为A.x=1
5、Console.WriteLine("AAA");
6、完成static A,返回第二步继续执行,所以B.y=2
7、Console.WriteLine("BBB");
8、Console.WriteLine("x={0},y={1}", A.x, B.y);不要被 Console.WriteLine("x={0},y={1}", A.x, B.y);这句话迷惑,因为Main在B当中,所以出发整个过程的不是这句Console中的A.x和B.y。不信你把它注释掉就明白了