什麼是 C# 中的抽象?


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

使用 C# 中的抽象類可以實現抽象。C# 允許您建立用來提供介面部分類實現的抽象類。當匯出類從中繼承時,實現便已完成。抽象類包含抽象方法,由派生類實現。派生類有更專門的功能。

以下是一些重點 −

  • 你無法建立抽象類的例項

  • 你無法在抽象類之外宣告抽象方法

  • 當類被宣告為 sealed 時,它無法被繼承,抽象類不能被宣告為 sealed。

示例

 線上演示

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+ 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告