1.实例构造函数
2.静态构造函数
3.私有构造函数
例:
创建一个类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _20180718Demo 8 { 9 public class TestConstructor 10 { 11 public int a; 12 public int b; 13 14 public static int c; 15 16 //静态构造函数(不可带修饰符) 17 static TestConstructor() 18 { 19 Console.WriteLine("静态构造函数被调用!"); 20 } 21 22 23 //无参构造函数 24 public TestConstructor() 25 { 26 27 } 28 29 public TestConstructor(int ia, int ib, int ic) 30 { 31 this.a = ia; 32 this.b = ib; 33 } 34 35 public TestConstructor(int ia, int ib) 36 { 37 this.a = ia; 38 this.b = ib; 39 } 40 41 public int Add() 42 { 43 return a + b; 44 } 45 } 46 }
1.在主函数种为静态变量c赋值并输出。
System.Console.WriteLine(TestConstructor.c=99);
运行一下:如图所示:
结论:访问该静态变量之前被调用
2.在主函数种实例化TestConstructor类,并且调用Add()方法。
TestConstructor Tc = new TestConstructor(6, 2);
System.Console.WriteLine(Tc.Add());
运行一下,如图所示:
结论:①第一次实例化该类时,静态函数被调用
②构造函数可以进行重载,类实例化时可以为成员变量赋值
3.私有构造函数。使用场景(工具类、单例模式)
创建一个单例类:
1 class SingleT 2 { 3 public static SingleT s = null; 4 private SingleT() 5 { 6 7 } 8 9 public static SingleT GetInstance() 10 { 11 if(s==null) 12 { 13 return s = new SingleT(); 14 } 15 16 return s; 17 } 18 }
结论:私有构造函数,可用于直接阻止创建类的实例
参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/private-constructors