做两道例题吧:
exp1:
using System; namespace testStatic { class Program { static void Main(string[] args) { Console.WriteLine(A.X.ToString()); //Return: 2 Console.WriteLine(B.Y.ToString()); //Return: 1 Console.Read(); } } class A { public static int X = B.Y; static A() { ++X; } } class B { public static int Y = A.X; static B() { ++Y; } } }
exp2:
using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace testStatic { class Program { static void Main(string[] args) { //Console.WriteLine(A.X.ToString()); //Console.WriteLine(B.Y.ToString()); A objA = A.Instance; Console.WriteLine(objA.GetStr()); Console.Read(); } } class A { static A instance = null; string str = "i am A, i am a member of class A"; public static int X = B.Y; /// <summary> /// 静态构造函数仅次于静态数据成员被调用. /// </summary> static A() { ++X; Console.WriteLine("hello A. I am from static A constructor"); } private A() { Console.WriteLine("hello A. I am from private A constructor"); } public string GetStr() { return str; } public static A Instance { get { //这里只有对类进行实例化的时候,非静态的构造函数才会被调用 return instance = new A(); } } } class B { //静态成页最先被调用 public static int Y = A.X; /// <summary> /// 静态构造函数后于静态成员被调用 /// </summary> static B() { ++Y; Console.WriteLine("hello B . I am from static B constructor"); } /// <summary> /// 只有对象被实例化的时候才会调用非静态构造函数 /// </summary> private B() { Console.WriteLine("hello B . I am from private B constructor"); } } }
输出为:
hello B . I am from static B constructor
hello A. I am from static A constructor
hello A. I am from private A constructor
i am A, i am a member of class A
我的解题思路:
A a= A.instance;
类A首先执行类里面每一个静态成员,
public static int x = B.y
静态成员初始化,并赋值(B.y执行顺序跟A一样,在B类里执行静态成员,静态构造函数后给A赋值)
之后在执行A的静态构造函数
诺在访问A类静态成员和静态构造函数不执行(静态成员和静态构造函数只执行一次)
A a = new A();
对象被实例化,非静态构造函数才会执行