深入解析C#中的abstract抽象类

2019-12-30 11:41:57王旭


csc abstractshape.cs shapes.cs shapetest.cs

这样将生成可执行文件 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 = " + string.Format("{0:F2}", Area);
  }
}

属性的修饰符就放置在属性声明中。例如:


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