如何在 C# 中继承类?


继承允许我们基于另一个类来定义类,这使创建和维护应用程序更容易。

在创建类时,编程员无需编写全新的数据成员和成员函数,他可以指定新类应该继承现有类成员。此现有类称为基类,新类称为派生类。一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口中继承数据和函数。

以下是一个示例:-

示例

 在线演示

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;
   }
   
   // Derived class
   class Rectangle: Shape {
      public int getArea() {
         return (width * height);
      }
   }
   class Demo {
      static void Main(string[] args) {
         Rectangle Rect = new Rectangle();

         Rect.setWidth(5);
         Rect.setHeight(7);
         // Print the area of the object.
         Console.WriteLine("Total area: {0}", Rect.getArea());
         Console.ReadKey();
      }
   }
}

输出

Total area: 35

更新日期: 22-6-2020

107 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.