zoukankan      html  css  js  c++  java
  • 闲说多态

    1、多态分为覆写和重载,重载即方法名相同,方法参数个数或类型或顺序不同。

    2、多态的表现形式之一:将父类类型作为方法的参数。

    Eg:家用电器

     1 class Person
     2 
     3 {
     4 
     5 public void RunElectrical(Electrical d)
     6 
     7 {
     8 
     9  Console.WriteLine("给电器插电");
    10 
    11  d.Run();
    12 
    13 }
    14 
    15 }
    16 
    17 //电器类 
    18 class Electrical
    19 20 { 21 22 public virtual void Run() 23 24 { 25 26 Console.WriteLine("电器运行"); 27 28 } 29 30 } 31 32 //空调类 33 class AirConditioning:Electrical 34 35 { 36 37 public override void Run() 38 39 { 40 41 Console.WriteLine("空调运行"); 42 43 } 44 45 } 46 47 //冰箱类
    48 class IceBox:Electrical 49 50 { 51 52 public override void Run() 53 54 { 55 56 Console.WriteLine("冰箱运行"); 57 58 } 59 60 } 61 62 63 class Program 64 65 { 66 67 static void Main(string[] agrs) 68 69 { 70 71 IceBox iceBox=new IceBox(); 72 73 Person p=new Person(); 74 75 p.RunElectrical(iceBox); 76 77 Console.ReadKey(); 78 79 } 80 81 }

    结果:

    3、将父类类型作为返回值

    Eg:交通工具

      1 //宠物类
      2 
      3 class Pet
      4 
      5 {
      6 
      7   public virtual void Shout()
      8 
      9   {
     10 
     11       Console.WriteLine("宠物叫");
     12 
     13   }
     14 
     15 }
     16 
     17 //猫类
     18 
     19 class Cat:Pet
     20 
     21 {
     22 
     23    public override void Shout()
     24 
     25    {
     26 
     27        Console.WriteLine("我是一只猫咪,喵喵");
     28 
     29    }
     30 
     31 }
     32 
     33 //狗类
     34 
     35 class Dog:Pet
     36 
     37 {
     38 
     39    public override void Shout()
     40 
     41    {
     42 
     43       Console.WriteLine("我是旺财,旺旺");
     44 
     45    }
     46 
     47 }
     48 
     49 //商店类
     50 
     51 class Shop
     52 
     53 {
     54 
     55  public Pet SellPet(string type)
     56 
     57 {
     58 
     59   switch(type)
     60 
     61   {
     62 
     63       case "dog":
     64 
     65        return new Dog();
     66 
     67       case "cat":
     68 
     69         return Cat();
     70 
     71       defalut:
     72 
     73          return null;
     74 
     75   }
     76 
     77 }
     78 
     79 }
     80 
     81 
     82 class Program
     83 
     84 {
     85 
     86   static void Main(string[] agrs)
     87 
     88   {
     89 
     90     shop shop=new Shop();
     91 
     92     Pet pet=Shop.SellPet("cat");
     93 
     94     pet.Shout();
     95 
     96     Console.ReadKey();
     97 
     98   }
     99 
    100 }
  • 相关阅读:
    ES6 Set.Map.Symbol数据结构
    ES6 class类 静态方法及类的继承
    ES6 浅谈Reflect
    ES6 proxy代理详解及用法
    Vue之生命周期函数
    Vue之自定义键盘修饰符、自定义指令
    v-show和v-if区别
    迭代器iterator
    es6之Proxy代理
    es6之symbol数据类型
  • 原文地址:https://www.cnblogs.com/ruanmou001/p/3352443.html
Copyright © 2011-2022 走看看