Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

พร็อพเพอร์ตี้เชิงนามธรรม (Abstract Properties) ใน C# คืออะไร

การประกาศพร็อพเพอร์ตี้เชิงนามธรรมจะไม่มีการนำเสนอการใช้งานของตัวเข้าถึงพร็อพเพอร์ตี้

ตัวอย่างการทำงานกับพร็อพเพอร์ตี้เชิงนามธรรม มีคลาสนามธรรม Shape พร้อมคลาสสืบทอด 2 คลาส: Square และ Circle

มีพร็อพเพอร์ตี้ Area แบบนามธรรม

คลาส Circle

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

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; } 
    } 
}

คลาส Shape (นามธรรม)

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); 
    } 
}