类在初始化时的执行顺序,依次如下:
1: 子类静态变量
2: 子类静态构造函数
3: 子类非静态变量
4: 父类静态变量
5: 父类静态构造函数
6: 父类非静态变量
7: 父类构造函数
8: 子类构造函数
对于静态变量与静态构造函数而言, 无论对一个类创建多少个实例,它的静态成员都只有一个副本。 也就是说,静态变量与静态构造函数只初始化一次(在类第一次实例化时)
以下代码:
class Class1
{
public static int Count = 0;
static Class1()
{
Count++;
}
public Class1()
{
Count++;
}
}
实例化代码:
Class1 c = new Class1();
Class1 cc = new Class1();
Console.WriteLine(Class1.Count.ToString());
Console.Read();
当第一次实例化时, Count值变成2, 当第二次实例化时, 则不会执行静态构造函数与静态变量. 此时Count的值变成3. 所以,最后结果Count值为3。
转载自:http://www.cnblogs.com/ybhcolin/archive/2010/09/24/1834219.html