如何在 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.