码迷,mamicode.com
首页 > 其他好文 > 详细

C#语言基础知识(2):C#中多态

时间:2014-07-07 00:44:06      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   line   div   

我的理解是:通过继承实现的不同对象调用相同的方法,表现出不同的行为,称之为多态.
1: OverRide 实现多态

 1 public class Animal
 2     {
 3         public virtual void Eat()
 4         {
 5             Console.WriteLine("Animal eat");
 6         }
 7     }
 8     public class Dog : Animal
 9     {
10         public override void Eat()
11         {
12             Console.WriteLine("Dog eat");
13         }
14     }
15     public class WolfDog : Dog
16     {
17         public override void Eat()
18         {
19             Console.WriteLine("WolfDog eat");
20         }
21     }
22     class Tester
23     {
24         static void Main(string[] args)
25         {
26             Animal[] animals = new Animal[3];
27             animals[0] = new Animal();
28             animals[1] = new Dog();
29             animals[2] = new WolfDog();
30             for (int i = 0; i < 3; i++)
31             {
32                 animals[i].Eat();
33             }
34         }
35 }

运行结果为:
Animal eat...
Dog eat...
WolfDog eat...
2:New虚方法实现多态

 1 public class Animal
 2     {
 3         public virtual void Eat()
 4         {
 5             Console.WriteLine("Animal eat");
 6         }
 7     }
 8     public class Cat : Animal
 9     {
10         public new void Eat()
11         {
12             Console.WriteLine("Cat eat");
13         }
14     }
15     class Tester
16     {
17         static void Main(string[] args)
18 
19         {
20             Animal a = new Animal();
21             a.Eat();
22             Animal ac = new Cat();
23             ac.Eat();
24             Cat c = new Cat();
25             c.Eat();
26         }
27     }

输出结果如下
Animal eat...
Animal eat...
Cat eat...

C#语言基础知识(2):C#中多态,布布扣,bubuko.com

C#语言基础知识(2):C#中多态

标签:style   blog   color   for   line   div   

原文地址:http://www.cnblogs.com/liubeimeng/p/3822308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!