C# 中的继承是什么?

csharpprogrammingserver side programming更新于 2025/10/14 20:52:17

通过继承,您可以根据另一个类来定义一个类,这使得应用程序的创建和维护更加容易。这还提供了重用代码功能并加快实现速度的机会。

继承基于基类以及派生类的概念。一个类可以从多个类或接口派生,这意味着它可以从多个基类或接口继承数据和函数。

让我们看一个基类和派生类的示例。这里,Shape 是基类,而 Rectangle 是派生类 −

class Rectangle: Shape {
   // 方法
}

以下示例展示了如何在继承中使用基类和派生类 −

示例

using System;

namespace InheritanceApplication {
   class Shape {
      public void setWidth(int w) {
         width = w;
      }
      public void setHeight(int h) {
         height = h;
      }
      protected int width;
      protected int height;
   }

   // 派生类
   class Rectangle: Shape {
      public int getArea() {
         return (width * height);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();
         Rect.setWidth(5);
         Rect.setHeight(7);
         // 打印对象的面积。
         Console.WriteLine("Total area: {0}", Rect.getArea());
         Console.ReadKey();
      }
   }  
}

输出

Total area: 35

相关文章