文件 1:abstractshape.cs 该文件声明包含 double 类型的 Area 属性的 Shape 类 // abstractshape.cs// compile with: /target:library// csc /target:library abstractshape.csusing System;public abstract class Shape{ private string myId; public Shape(string s) { Id = s; // calling the set accessor of the Id property } public string Id { get { return myId; } set { myId = 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); }} 代码讨论文件 2:shapes.cs 下面的代码展示 Shape 的三个子类,并展示它们如何重写 Area 属性来提供自己的实现。 // shapes.cs// compile with: /target:library /reference:abstractshape.dllpublic class Square : Shape{ private int mySide; public Square(int side, string id) : base(id) { mySide = side; } public override double Area { get { // Given the side, return the area of a square: return mySide * mySide; } }}public class Circle : Shape{ private int myRadius; public Circle(int radius, string id) : base(id) { myRadius = radius; } public override double Area { get { // Given the radius, return the area of a circle: return myRadius * myRadius * System.Math.PI; } }}public class Rectangle : Shape{ private int myWidth; private int myHeight; public Rectangle(int width, int height, string id) : base(id) { myWidth = width; myHeight = height; } public override double Area { get { // Given the width and height, return the area of a rectangle: return myWidth * myHeight; } }} 文件 3:shapetest.cs 以下代码展示一个测试程序,它创建若干 Shape 派生的对象,并输出它们的面积。 // shapetest.cs// compile with: /reference:abstractshape.dll;shapes.dllpublic class TestClass{ public 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); } }} 输出Shapes CollectionSquare #1 Area = 25.00Circle #1 Area = 28.27Rectangle #1 Area = 20.00  
2/2 首页 上一页 1 2 |