静态构造函数
1.类的构造函数有三种:实例构造函数,私有构造函数和静态构造函数,静态构造函数只能初始化静态数据,或执行一次特殊的操作,这种函数只执行一次,在第一次创建类的对象的时候或者调用静态成员时就会自动调用它,静态构造函数没有访问修饰符,也没有任何参数。
可以参考一下下面的代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 静态构造函数 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 SayHello MyClass1 = new SayHello(); 13 SayHello MyClass2 = new SayHello(); 14 Console.ReadKey(); 15 } 16 } 17 18 class SayHello 19 { 20 public SayHello() 21 { 22 Console.WriteLine("构造函数"); 23 } 24 static SayHello() 25 { 26 Console.WriteLine("静态构造函数"); 27 } 28 } 29 }
执行结果为:
静态构造函数
构造函数
构造函数
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 静态构造函数 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 SayHello.Name = "Tom"; 13 Console.ReadKey(); 14 } 15 } 16 17 class SayHello 18 { 19 public static string Name; 20 21 static SayHello() 22 { 23 Console.WriteLine("静态构造函数"); 24 } 25 } 26 }
执行结果为:
静态构造函数