在 C# 中,可以将字段和方法从一个类继承到另一个类。我们将 "inheritance concept" 分为两类:
要从类继承,请使用:
象征。
在下面的示例中,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
类,C#会产生错误:
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}
错误消息将是这样的:
'Car': cannot derive from sealed type 'Vehicle'
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!