Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Abstract Property (Thuộc tính trừu tượng) trong C#

Abstract property declaration không cung cấp implementation cho property accessors.

Ví dụ: Abstract class Shape với hai derived class: Square và Circle. Có abstract property Area.

Circle class

public class Circle : Shape {
    private int radius;
    public Circle(int radius, string id) : base(id) { this.radius = radius; }
    public override double Area {
        get { return radius * radius * System.Math.PI; }
    }
}

Square class

public class Square : Shape {
    private int side;
    public Square(int side, string id) : base(id) { this.side = side; }
    public override double Area {
        get { return side * side; }
    }
}

Abstract Shape class

public abstract class Shape {
    private string name;
    public Shape(string s) { Id = s; }
    public string Id {
        get { return name; }
        set { name = value; }
    }
    public abstract double Area { get; }
    public override string ToString() {
        return Id + " Area = " + string.Format("{0:F2}", Area);
    }
}