什麼是 C# 中的抽象?


抽象和封裝是面向物件程式設計中的相關特性。抽象可以使相關資訊可見,而封裝使程式設計師能夠實現所需的抽象級別。

使用 C# 中的抽象類可以實現抽象。C# 允許你建立用於提供介面部分類實現的抽象類。當派生類從抽象類繼承時,實現完成了。抽象類包含抽象方法,這些方法由派生類實現。派生類具有更專門的功能。

以下是一些關鍵點 −

  • 你不能建立一個抽象類的例項

  • 你不能在抽象類外宣告一個抽象方法

  • 當一個類被宣告為密封的,它不能被繼承,抽象類不能被宣告為密封的。

示例

 線上演示

using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(20, 15);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}

輸出

Rectangle class area :
Area: 300

更新於:2020 年 6 月 22 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程後獲得證書

開始學習
廣告
© . All rights reserved.