C#抽象類

iamzxf發表於2015-04-08

     抽象類是C#語言中的一個重要的概念,抽象類不允許被例項化,希望以它為基類的所有派生類具有共同的成員和資料成員。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//抽象類
namespace chap4_5
{
    abstract class Shape
    {
        public string Id { get; set; }
        public abstract double Area { get; }
        public override string ToString()
        {
            return Id + string.Format("{0,10:F2}",Area);
        }
        public Shape(string id)
        {
            Id=id;
        }
    }

    class Square : Shape {
        private int m_side;
        public Square(int side, string id)
            : base(id)
        {
            m_side = side;
        }

        public override double Area
        {
            get {
                return m_side * m_side;
            }
        }
    }

    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 * Math.PI; }
        }
    }


    class Rectangle : Shape {
        private int a;
        private int b;
        public Rectangle(int a, int b, string id)
            : base(id)
        {
            this.a = a;
            this.b = b;
        }

        public override double Area
        {
            get {
                return a * b;
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Shape[] shapes ={
                              new Square(5,"sp01")  ,
                              new Rectangle(2,3,"sp02"),
                              new Circle(2,"sp03")
                            };

            foreach (Shape s in shapes)
            {
                Console.WriteLine(s.ToString());
            }            

            Console.ReadLine();

        }
    }
}



相關文章