C#基础:多态:基类可以定义并实现虚(virtual)方法,派生类可以重写(override)这些方法

 

 

原理:基类可以定义并实现虚(virtual)方法,派生类可以重写(override)这些方法

实例代码:

 

class Shape

    {

        //

        public int X{get;private set; }

        public int Y{get;private set;}

        public int Height{get;set;}

        public int Width{get;set;}

        //

        public virtual void Draw()

        {

            Console.WriteLine("Performing base class drawing tasks");

        }

    }

    class Circle : Shape

    {

        public override void Draw()

        {

            // Code to draw a circle...

            Console.WriteLine("Drawing a circle");

            base.Draw();

        }

    }

    class Rectangle : Shape

    {

        public override void Draw()

        {

            // Code to draw a rectangle...

            Console.WriteLine("Drawing a rectangle");

            base.Draw();

        }

    }

    class Triangle : Shape

    {

        public override void Draw()

        {

            // Code to draw a triangle...

            Console.WriteLine("Drawing a triangle");

            base.Draw();

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            List<Shape> shapes = new List<Shape>();

            shapes.Add(new Rectangle());

            shapes.Add(new Triangle());

            shapes.Add(new Circle());

            foreach (Shape s in shapes)

            {

                s.Draw();

            }

            Console.WriteLine("press any key to exit.");

            Console.ReadKey();

        }

    }

 

posted @ 2013-02-19 19:54  乡香田甜  阅读(341)  评论(0编辑  收藏  举报