什么是 C# 中的基类?


创建类时,编程人员可以指定新类应继承现有类的成员,而不是编写全新的数据成员和成员函数。此现有类称为基类,而新类称为派生类。

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

以下是 C# 中基类的语法 −

<access-specifier> class <base_class> {
   ...
}

class <derived_class> : <base_class> {
   ...
}

我们来看一个示例 −

示例

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 RectangleTester {
      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();
      }
   }
}

更新于: 20-6 月-2020

1000+ 次浏览

启动您的 职业生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.