分享方式:


如何定義抽象屬性 (C# 程式設計手冊)

下列範例示範如何定義 抽象 屬性。 抽象屬性宣告不提供屬性存取子的實作-- 它會宣告類別支援屬性,但會將存取子實作留給衍生類別。 下列範例示範如何實作繼承自基類的抽象屬性。

此範例包含三個檔案,每個檔案都會個別編譯,且下一個編譯會參考其產生的元件:

  • abstractshape.cs: Shape 包含抽象 Area 屬性的類別。

  • shapes.cs:類別的 Shape 子類別。

  • shapetest.cs:顯示某些 Shape衍生對象的區域的測試程式。

若要編譯範例,請使用下列命令:

csc abstractshape.cs shapes.cs shapetest.cs

這會 shapetest.exe建立可執行檔。

範例

這個檔案會 Shape 宣告類別,其中包含 Areadouble別 的屬性。

// compile with: csc -target:library abstractshape.cs
public abstract class Shape
{
    public Shape(string s)
    {
        // calling the set accessor of the Id property.
        Id = s;
    }

    public string Id { get; set; }

    // Area is a read-only property - only a get accessor is needed:
    public abstract double Area
    {
        get;
    }

    public override string ToString()
    {
        return $"{Id} Area = {Area:F2}";
    }
}
  • 屬性上的修飾詞會放在屬性宣告本身上。 例如:

    public abstract double Area  
    
  • 宣告抽象屬性時(例如 Area 在此範例中),您只需指出可用的屬性存取子,但不會實作它們。 在此範例中,只有 get 存取子可用,因此屬性是唯讀的。

下列程式代碼顯示了 Shape 的三個子類別,以及它們如何覆寫 Area 屬性來提供自己的實作。

// compile with: csc -target:library -reference:abstractshape.dll shapes.cs
public class Square : Shape
{
    private int _side;

    public Square(int side, string id)
        : base(id)
    {
        _side = side;
    }

    public override double Area
    {
        get
        {
            // Given the side, return the area of a square:
            return _side * _side;
        }
    }
}

public class Circle : Shape
{
    private int _radius;

    public Circle(int radius, string id)
        : base(id)
    {
        _radius = radius;
    }

    public override double Area
    {
        get
        {
            // Given the radius, return the area of a circle:
            return _radius * _radius * Math.PI;
        }
    }
}

public class Rectangle : Shape
{
    private int _width;
    private int _height;

    public Rectangle(int width, int height, string id)
        : base(id)
    {
        _width = width;
        _height = height;
    }

    public override double Area
    {
        get
        {
            // Given the width and height, return the area of a rectangle:
            return _width * _height;
        }
    }
}

下列程式代碼顯示一個測試程式,它建立了一些 Shape 衍生物件,然後列印出其面積。

// compile with: csc -reference:abstractshape.dll;shapes.dll shapetest.cs
class TestClass
{
    static void Main()
    {
        Shape[] shapes =
        [
            new Square(5, "Square #1"),
            new Circle(3, "Circle #1"),
            new Rectangle( 4, 5, "Rectangle #1")
        ];

        Console.WriteLine("Shapes Collection");
        foreach (Shape s in shapes)
        {
            Console.WriteLine(s);
        }
    }
}
/* Output:
    Shapes Collection
    Square #1 Area = 25.00
    Circle #1 Area = 28.27
    Rectangle #1 Area = 20.00
*/

另請參閱