什麼是 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.