我的網(wǎng)站首頁打不開b站2023年免費(fèi)入口
以下示例演示如何定義抽象屬性。 抽象屬性聲明不提供屬性訪問器的實(shí)現(xiàn),它聲明該類支持屬性,而將訪問器實(shí)現(xiàn)留給派生類。 以下示例演示如何實(shí)現(xiàn)從基類繼承抽象屬性。
此示例由三個(gè)文件組成,其中每個(gè)文件都單獨(dú)編譯,產(chǎn)生的程序集由下一次編譯引用:
- abstractshape.cs:包含抽象 Area 屬性的 Shape 類;
- shapes.cs:Shape 類的子類;
- shapetest.cs:測試程序,用于顯示一些 Shape 派生對象的區(qū)域;
若要編譯該示例,請使用以下命令:
csc abstractshape.cs shapes.cs shapetest.cs
這將創(chuàng)建可執(zhí)行文件 shapetest.exe。
示例
此文件聲明 Shape 類,該類包含 double 類型的 Area 屬性。
// 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
聲明抽象屬性時(shí)(如本示例中的 Area),只需指明哪些屬性訪問器可用即可,不要實(shí)現(xiàn)它們。 在此示例中,僅 get 訪問器可用,因此該屬性是只讀屬性。
下面的代碼演示 Shape 的三個(gè)子類,并演示它們?nèi)绾翁娲?Area 屬性來提供自己的實(shí)現(xiàn)。
// 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;}}
}
下面的代碼演示一個(gè)創(chuàng)建若干 Shape 派生對象并輸出其區(qū)域的測試程序。
// 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 CollectionSquare #1 Area = 25.00Circle #1 Area = 28.27Rectangle #1 Area = 20.00
*/