Logo
Section 1 / 19

继承

学习如何在 C# 中实现继承,以建立类之间的层次关系,并最大化类之间的代码复用。

导入

继承

学习如何在 C# 中实现继承,以建立类之间的层次关系,并最大化类之间的代码复用。

代码示例

1public class Car 2{ 3 public string Model { get; set; } 4 public decimal Price { get; set; } 5 public int Year { get; set; } 6 public int FuelCapacityInLiters { get; set; } 7 public int FuelLeft { get; set; } 8 9 public void Drive() 10 { 11 } 12}
1namespace Inheritance 2{ 3 public class Vehicle 4 { 5 public string Model { get; set; } 6 public decimal Price { get; set; } 7 public int Year { get; set; } 8 public int FuelCapacityInLiters { get; set; } 9 public int FuelLeft { get; set; } 10 public short NumberOfWheels { get; set; } 11 12 public void Drive() 13 { 14 } 15 } 16}
1namespace Inheritance 2{ 3 // Car 继承自 Vehicle 4 // Vehicle 是 Car 的基类 5 public class Car : Vehicle 6 { 7 } 8}
1namespace Inheritance 2{ 3 public class Motorcycle : Vehicle 4 { 5 } 6}
...
类图展示继承关系
1using Inheritance; 2 3// 创建 Car 实例 4Car myCar = new Car(); 5myCar.Model = "Toyota Prius"; 6myCar.Price = 12000; 7 8Console.WriteLine($"{myCar.Model} costs {myCar.Price} dollars."); 9 10// 创建 Motorcycle 实例 11Motorcycle myBike = new Motorcycle(); 12myBike.Model = "Harley Davidson"; 13myBike.Price = 20000; 14 15Console.WriteLine($"{myBike.Model} costs {myBike.Price} dollars.");

代码示例

1Vehicle myCar = new Car();

从 System.Object 的隐式继承

1// 从 Object 继承 2public class SomeClass 3{ 4}
1using Inheritance; 2 3Car myCar = new Car(); 4Car anotherCar = new Car(); 5 6// 调用 Object 类的方法 7Console.WriteLine(myCar.ToString()); 8Console.WriteLine(myCar.Equals(anotherCar)); 9Console.WriteLine(myCar.GetHashCode()); 10Console.WriteLine(myCar.GetType());
...
继承 Object 的方法
1public sealed class SomeClass 2{ 3} 4 5public class MyClass : SomeClass // 错误:无法从密封类型 'SomeClass' 继承 6{ 7}

使用组合包含功能

1namespace Inheritance; 2 3public class Engine 4{ 5 public void Start() 6 { 7 Console.WriteLine("引擎启动。"); 8 } 9} 10 11// 组合:Car “拥有一个” 引擎 12public class Car : Vehicle 13{ 14 public Engine CarEngine { get; set; } = new Engine(); 15 public int NumberOfDoors { get; set; } 16}

接口

继承的其他主题