C# 关键字new修饰方法时候和override的区别

理论:

使用new修饰的方法,在使用面向对象的多态的时候,引用指向什么类型就调用什么类型的对应方法,子类没有定义方法为public的时候,优先调用公有方法;

使用override修饰的方法,无论引用是什么类型,编译器均找到该对象的实际类型,调用其中的方法。

 

代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication17 {
 7     class Program {
 8         static void Main(string[] args) {
 9             Father f = new Father();
10             f.MInFather();
11             //((Son)f).MInFather();   
12             //报错,无法将Father强制转换为Son,
13             //转换的实质是本身就是这样的对象,但是有1个不是这个对象类型的引用地址
14 
15             Father f2 = new Son();
16             f2.MInFather();         //输出:In father
17             ((Son)f2).MInFather();  //输出:In son(必须用public 修饰,否则显示In father)
18 
19             Son son = new Son();
20             son.MInFather();        //输出:In son(必须用public 修饰,否则显示In father)
21             ((Father)son).MInFather();  //输出:In father
22 
23             Console.WriteLine("-------------------------");
24 
25             Animal ani = new Animal();
26             ani.MInFather();        //输出:In Animal
27 
28             Animal ani2 = new Bird();
29             ani2.MInFather();       //输出:In Bird
30             ((Bird)ani2).MInFather();//输出:In Bird
31 
32 
33             Bird bb = new Bird();
34             bb.MInFather();         //输出:In Bird
35             ((Animal)bb).MInFather();   //输出:In Bird
36         }
37     }
38 
39     class Father {
40         public virtual void MInFather() {
41             Console.WriteLine("This is method in father.");
42         }
43     }
44 
45     class Son : Father {
46         //如果没有此处的public ,将全部显示 in father,因为此方法是私有的,且从父类集成来的 公有方法>>>优先访问
47         public new void MInFather() {
48             Console.WriteLine("in son.");
49         }
50     }
51 
52     class Animal {
53         public virtual void MInFather() {
54             Console.WriteLine("This is method in Animal.");
55         }
56     }
57 
58     class Bird : Animal {
59         //如果没有public,此处将产生编译错误, 因为不能把父类的public 的虚拟方法重写成本类私有的
60         public override void MInFather() {
61             Console.WriteLine("in Bird.");
62         }
63     }
64 }

运行结果:

 

 

 

 

<完>

posted @ 2014-08-22 14:02  Thirty  阅读(304)  评论(0)    收藏  举报