关于静态构造函数一直有些不特别明白,现在上一次实例,仅供参考。
代码
1 public class TestStaticConstructor
2 {
3 public static int intTemp = 0;
4
5 //public static TestStaticConstructor()
6 static TestStaticConstructor() // Cannot use access modifier in static constructor
7 {
8 Console.WriteLine("static:" + TestStaticConstructor.intTemp.ToString());
9 intTemp++;
10 }
11
12 public TestStaticConstructor()
13 {
14 Console.WriteLine("non-static:" + TestStaticConstructor.intTemp.ToString());
15 intTemp++;
16 }
17 }
2 {
3 public static int intTemp = 0;
4
5 //public static TestStaticConstructor()
6 static TestStaticConstructor() // Cannot use access modifier in static constructor
7 {
8 Console.WriteLine("static:" + TestStaticConstructor.intTemp.ToString());
9 intTemp++;
10 }
11
12 public TestStaticConstructor()
13 {
14 Console.WriteLine("non-static:" + TestStaticConstructor.intTemp.ToString());
15 intTemp++;
16 }
17 }
下面是测试代码
第一种情况:只声明
代码
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
Console.Read();
}
static void Main(string[] args)
{
// change this line next
TestStaticConstructor tc;
{
// change this line next
TestStaticConstructor tc;
// same as code behind
//TestStaticConstructor tc = null;
//TestStaticConstructor tc = null;
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
Console.Read();
}
输出:
static:0
Current:1
Current:1
第二种情况:声明一次
TestStaticConstructor tc = new TestStaticConstructor();
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
Console.Read();
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
Console.Read();
输出:
static:0
non-static:1
Current:2
non-static:1
Current:2
第三种情况:声明两次
代码
TestStaticConstructor tc = new TestStaticConstructor();
TestStaticConstructor tc1 = new TestStaticConstructor();
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
TestStaticConstructor tc1 = new TestStaticConstructor();
Console.WriteLine("Current:" + TestStaticConstructor.intTemp.ToString());
输出:
static:0
non-static:1
non-static:2
Current:3