C# 遗产
继承(派生类和基类)
在 C# 中,可以将字段和方法从一个类继承到另一个类。我们将“继承概念”分为两类:
- 派生类 (子类)- 从另一个类继承的类
- 基类 (父类)- 继承自的类
要从类继承,请使用 :
象征。
在下面的例子中, Car
类(子类)从Vehicle
班级(父母):
例子
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
sealed 关键字
如果不希望其他类继承自某个类,可以使用 sealed
关键词:
如果你尝试访问 sealed
类,C# 将产生一个错误:
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}
错误信息将会是这样的:
'Car': cannot derive from sealed type 'Vehicle'