C# 继承
继承(派生类和基类)
在 C# 中,可以从一个类继承字段和方法到另一个类。我们将“继承概念”分为两类:
- 派生类(子类)- 从另一个类继承的类
- 基类(父类)- 被继承的类
要从类继承,请使用 :
符号。
在下面的例子中,Car 类(子类)从 Vehicle
类(父类)继承字段和方法:
实例
class Vehicle // 基类 (父类) { public string brand = "Ford"; // Vehicle 字段 public void honk() // Vehicle 方法 { Console.WriteLine("Tuut, tuut!"); } } class Car : Vehicle // 派生类 (子类) { public string modelName = "Mustang"; // Car 字段 } class Program { static void Main(string[] args) { // 创建一个 myCar 对象 Car myCar = new Car(); // 在 myCar 对象上调用 honk() 方法(来自 Vehicle 类) myCar.honk(); // 显示 brand 字段的值(来自 Vehicle 类)和来自 Car 类的 modelName 的值 Console.WriteLine(myCar.brand + " " + myCar.modelName); } }
为什么以及何时使用“继承”?
- 它对于代码可重用性很有用:创建新类时重用现有类的字段和方法。
提示:另请参阅下一章多态性,它使用继承的方法来执行不同的任务。
sealed 关键字
如果您不希望其他类从某个类继承,请使用 sealed
关键字:
如果您尝试访问一个密封类,C# 将生成一个错误:
sealed class Vehicle { ... } class Car : Vehicle { ... }
错误消息将类似于以下内容:
'Car': cannot derive from sealed type 'Vehicle'
('Car':不能从密封类型'Vehicle'派生)