C# 中的基礎類和派生類是什麼?


一個類可以從多個類或介面中派生得出,這意味著它可以從多個基類或介面中繼承資料和函式。

例如,帶有如下派生類的車輛基類。

Truck
Bus
Motobike

派生類繼承基類的成員變數和成員方法。

同樣,對於 Shape 類,派生類可以是 Rectangle,如下例所示。

示例

 即時演示

using System;
namespace Program {
   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

更新於:2020 年 6 月 23 日

202 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

入門
廣告
© . All rights reserved.