C# 继承
创建于 2024-12-03 /
34
字体:
[默认]
[大]
[更大]
继承(派生类和基类)
在 C# 中,可以将字段和方法从一个类继承到另一个类。我们将继承概念分为两类:
- 派生类(子类)-从另一个类继承的类
- 基类(父级)-从中继承的类
要从类继承,请使用:
符号。
在下面的示例中Car
类(child)从Vehicle
类(parent)继承字段和方法:
实例
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();
// 显示品牌字段的值(来自 Vehicle 类)和来自 Car 类的 modelName 的值
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
何时使用继承?
它对代码的可重用性很有用:在创建新类时重用现有类的字段和方法。
提示: 还要看下一章,多态性Polymorphism,它使用继承的方法来执行不同的任务。
密封关键字
如果不希望其他类从类继承,请使用sealed
关键字:
如果尝试访问 sealed
密封类,C# 将产成错误:
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}
错误消息如下所示:
'Car': cannot derive from sealed type 'Vehicle'
0 人点赞过