一個類如果沒有構造那么系統為我們在背后創建一個0參數的構造,但是一旦我們創建了但參數的構造,那么默認的構造就沒了。


1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ConsoleApplication4 7 { 8 class Person 9 { 10 private string _name; 11 public Person(string name) 12 { 13 _name = name; 14 } 15 public void Display() 16 { 17 Console.WriteLine("Name: {0}", _name); 18 } 19 } 20 class Employee : Person 21 { 22 public Employee(string name) : base(name) 23 { 24 25 } 26 } 27 class Program 28 { 29 30 static void Main(string[] args) 31 { 32 Employee emp = new Employee("Shawn"); 33 emp.Display(); 34 Console.ReadKey(); 35 } 36 } 37 }
構造函數不像方法或者property可以向繼承它的類傳遞,所以base class有構造的話,記得繼承類要調用base