菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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': 不能从 sealed 类型 'Vehicle' 派生


×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持