zoukankan      html  css  js  c++  java
  • 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();

            }

        }

     

  • 相关阅读:
    206. Reverse Linked List
    简介AngularJS中使用factory和service的方法
    如何写一手漂亮的模型:面向对象编程的设计原则综述
    webpack入门操作教程
    webpack4.0.1安装问题和webpack.config.js的配置变化
    webpack.config.js配置遇到Error: Cannot find module '@babel/core'&&Cannot find module '@babel/plugin-transform-react-jsx' 问题
    解决webpack打包报错: Cannot find module '@webassemblyjs/wasm-parser'
    docker-compose介绍
    .NET Core+MySql+Nginx 容器化部署
    .net core使用ef core操作mysql数据库
  • 原文地址:https://www.cnblogs.com/lqsilly/p/2917609.html
Copyright © 2011-2022 走看看