class Father { public string name = "爸爸"; public void MakeMoney() { Console.WriteLine("我可以赚钱"); } } class Son : Father { new public string name = "儿子"; new public void MakeMoney() { Console.WriteLine("我也可以赚钱"); } }
class Program { static void Main(string[] args) { Man man1 = new Man(); Console.WriteLine(man1.Height); Man man2 = new Man(180); Console.WriteLine(man2.Height); } } class Human { public int Height; public Human(int height) { this.Height = height; } public Human() { this.Height = 165; } } class Man : Human { public Man() :base() {} public Man(int height) : base(height) {} }
还可以让构造过程使用当前类中其他的构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Program { static void Main(string[] args) { Human human = new Human(75,180); Console.WriteLine($"身高{human.Height},体重{human.Weight}"); } } class Human { public int Height; public int Weight; private Human(int height) { this.Height = height; } public Human(int weight,int height) :this(height){ this.Weight = weight; } }