C# - 类_使用新成员隐藏基类成员

 1 using System;
 2 
 3 namespace 类_使用新成员隐藏基类成员
 4 {
 5     // 基类 : Animal
 6     public class Animal
 7     {
 8         // 基类的普通方法Eat(), 并未用Virtual修饰
 9         public void Eat()
10         {
11             Console.WriteLine("动物吃的方法: ");
12         }
13     }
14 
15     // 子类 : Horse
16     public class Horse : Animal
17     {
18         // 子类的方法Eat()与基类的方法Eat()同名
19         // 使用关键字new修饰, 可以隐藏基类中的同名方法
20         public new void Eat()
21         {
22             // 调用Animal的Eat()
23             base.Eat();
24 
25             Console.WriteLine("【马】吃的方法!");
26         }
27     }
28 
29     public class Sheep : Animal
30     {
31         public new void Eat()
32         {
33             base.Eat();
34             Console.WriteLine("【羊】吃的方法!");
35         }
36     }
37 
38     class Program
39     {
40         static void Main(string[] args)
41         {
42             //
43             Horse horse = new Horse();
44             horse.Eat();
45 
46             Console.WriteLine();
47 
48             //
49             Sheep sheep = new Sheep();
50             sheep.Eat();
51 
52             Console.ReadLine();
53         }
54     }
55 }

posted @ 2016-04-06 09:53  C/C++/Python/Java  阅读(498)  评论(0编辑  收藏  举报