zoukankan      html  css  js  c++  java
  • c#中的多态

    概念

    多态是面向对象三大特性(封装、继承、多态)之一。是接口的不同实现方式,在uml中老师这样解释到:“通过继承


    实现不同对象调用不同方法来实现不同的行为”。


    例子

    public class Animal
        {
            public virtual void Eat()
            {
                Console.WriteLine("Animal eat");
            }
        }
    
        public class Cat : Animal
        {
            public override void Eat()
            {
                Console.WriteLine("Cat eat");
            }
        }
    
        public class Dog : Animal
        {
            public override void Eat()
            {
                Console.WriteLine("Dog eat");
            }
        }
    
        class Tester
        {
            static void Main(string[] args)
            {
                Animal[] animals = new Animal[3];
    
                animals[0] = new Animal();
                animals[1] = new Cat();
                animals[2] = new Dog();
    
                for (int i = 0; i < 3; i++)
                {
                    animals[i].Eat();
                }
            }
        }
    

    结果


    例子中,通过继承,使得Animal对象数组中的不同的对象,在调用Eat()方法时,表现出了不同的行为。


  • 相关阅读:
    设计模式-结构型模式总结
    设计模式-享元模式
    设计模式-组合模式
    设计模式-桥接模式
    设计模式-装饰器模式
    设计模式-外观模式
    设计模式-代理模式
    设计模式-适配器模式
    VMware该虚拟机似乎正在使用中
    BurpSuite-Burp Proxy
  • 原文地址:https://www.cnblogs.com/guziming/p/4232754.html
Copyright © 2011-2022 走看看