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

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

這個範例包含三個檔案,每個檔案都是各自編譯,產生的組件是下次編譯參考的對象:

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

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

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

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

csc abstractshape.cs shapes.cs shapetest.cs

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

範例

這個檔案會宣告包含 double 類型 Area 屬性的 Shape 類別。

// compile with: csc -target:library abstractshape.cs
public abstract class Shape
{
    private string name;

    public Shape(string s)
    {
        // calling the set accessor of the Id property.
        Id = s;
    }

    public string Id
    {
        get
        {
            return name;
        }

        set
        {
            name = value;
        }
    }

    // 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)
    {
        this.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)
    {
        this.radius = radius;
    }

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

public class Rectangle : Shape
{
    private int width;
    private int height;

    public Rectangle(int width, int height, string id)
        : base(id)
    {
        this.width = width;
        this.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")
        };

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

另請參閱