C#基础——virtual

     virtual关键字用于修饰方法、属性、索引器或事件声明,并使它们可以在派生类被重写。

     调用虚方法事时,将为重写成员检查该对象的运行时类型。

     virtual修饰符不能与static、abstract、private或override修饰符一起使用。

  1. class TestClass
    {
        public class Dimensions
        {
            public const double PI = Math.PI;
            protected double x, y;
            public Dimensions()
            {
            }
            public Dimensions(double x, double y)
            {
                this.x = x;
                this.y = y;
            }
            public virtual double Area()
            {
                return x * y;
            }
        }
  2.     public class Circle : Dimensions
        {
            public Circle(double r) : base(r, 0)
            {
            }
            public override double Area()
            {
                return PI * x * x;
            }
        }
        class Sphere : Dimensions
        {
            public Sphere(double r) : base(r, 0)
            {
            }
            public override double Area()
            {
                return 4 * PI * x * x;
            }
        }
        class Cylinder : Dimensions
        {
            public Cylinder(double r, double h) : base(r, h)
            {
            }
            public override double Area()
            {
                return 2 * PI * x * x + 2 * PI * x * y;
            }
        }
        static void Main()
        {
            double r = 3.0, h = 5.0;
            Dimensions c = new Circle(r);
            Dimensions s = new Sphere(r);
            Dimensions l = new Cylinder(r, h);
            Console.WriteLine("Area of Circle   = {0:F2}", c.Area());
            Console.WriteLine("Area of Sphere   = {0:F2}", s.Area());
            Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
            Console.ReadLine();
        }
  3. }

 image

posted @ 2010-01-06 22:02  Asharp  阅读(474)  评论(0编辑  收藏  举报