C#基礎:多型:基類可以定義並實現虛(virtual)方法,派生類可以重寫(override)這些方法...

weixin_34104341發表於2020-04-07

 

 

原理:基類可以定義並實現虛(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();

        }

    }

 

轉載於:https://www.cnblogs.com/lqsilly/archive/2013/02/19/2917609.html

相關文章