用法一: 函數
父類的構造函數老是在子類以前執行的。既先初始化靜態構造函數,後初始化子類構造函數。this
public class BaseCircle { public BaseCircle() { Console.WriteLine(" no arguments base constructor!!!"); } public BaseCircle(double arg) { Console.WriteLine("double arg base constructor!!!"); } } public class SubCircle : BaseCircle { public SubCircle():base() { Console.WriteLine("sub class no argument constructor,actually call base constructor !!!"); } public SubCircle(double a):base(a) { Console.WriteLine("sub class with argument, actually call base double constructor!!!"); } public SubCircle(int k):this(1,2) { Console.WriteLine("sub class with argument int k, actually call sub class constructor int i & j !!!"); } public SubCircle(int i,int j) { Console.WriteLine("sub class with int i&j argument!!!!"); } } static void Main(string[] args) { SubCircle s1 = new SubCircle(); SubCircle s2 = new SubCircle(1.1); SubCircle s3 = new SubCircle(1); }
輸出結果: no arguments base constructor!!! sub class no argument constructor,actually call base constructor !!! double arg base constructor!!! sub class with argument, actually call base double constructor!!! no arguments base constructor!!! sub class with int i&j argument!!!! sub class with argument int k, actually call sub class constructor int i & j !!!
用法二: spa
是否是很模糊這兩個關鍵字那?code
哈,如今我來寫份代碼,代碼但是最有說服力的啦!blog
class BaseClass { private int numA; public BaseClass() { Console.WriteLine("基類的無參數構造函數. value:{0}", numA); } public BaseClass(int i) { this.numA = i; Console.WriteLine("基類帶一個參數的構造函數. value:{0}", numA); } } class ChildClassA : BaseClass { private int numB; public ChildClassA() { Console.WriteLine("子類無參數構造函數. value:{0}", numB); } public ChildClassA(int i) { this.numB = i; Console.WriteLine("子類帶有一個參數的構造函數. value:{0}", numB); } public ChildClassA(int i, int j) : base(i) { this.numB = j; Console.WriteLine("子類帶有兩個參數的構造函數. value:{0}", numB); } } class ChildClassB : BaseClass { private int numB; public ChildClassB() { Console.WriteLine("子類無參數構造函數. value:{0}", numB); } public ChildClassB(int i) { this.numB = i; Console.WriteLine("子類帶有一個參數的構造函數. value:{0}", numB); } public ChildClassB(int i, int j) : this(i) { this.numB = j; Console.WriteLine("子類帶有兩個參數的構造函數. value:{0}", numB); } } class Demo { static void Main(string[] args) { Console.WriteLine("使用base\n"); ChildClassA a = new ChildClassA(2, 4); Console.WriteLine(); Console.WriteLine("----------------------------------------\n"); Console.WriteLine("使用this\n"); ChildClassB b = new ChildClassB(2, 4); Console.ReadKey(); } }
執行的結果以下:string
--------------------------------結果---------------------------------- 使用base 基類帶一個參數的構造函數. value:2 子類帶有兩個參數的構造函數. value:4 ---------------------------------------- 使用this 基類的無參數構造函數. value:0 子類帶有一個參數的構造函數. value:2 子類帶有兩個參數的構造函數. value:4 --------------------------------結果--------------------------------
this只是調用自己,可是這樣是須要調用一次基類沒有參的構造函數,因此會多顯示一條「基類的無參數構造函數. value:0」。
base是調用基類的有參數構造函數。
it