Menu
×
   ❮   
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': 无法从密封类型 'Vehicle' 派生。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.