1.编写个小程序,就可以理解new和override区别
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Newoverride
7 {
8 class Dad
9 {
10 public Dad()
11 {
12 Console.WriteLine("Dad construtor");
13 }
14 public virtual void method()
15 {
16 Console.WriteLine("Dad method");
17 }
18 }
19 class SmallSon : Dad
20 {
21 public SmallSon()
22 {
23 Console.WriteLine("Smallson construtor");
24 }
25 public override void method()
26 {
27 Console.WriteLine("override Smallson method");
28 }
29 }
30 class BigSon : Dad
31 {
32 public BigSon()
33 {
34 Console.WriteLine("BigSon construtor");
35 }
36 public new void method()
37 {
38 Console.WriteLine("new BigSon method ");
39 }
40 }
41 class Program
42 {
43 static void Main(string[] args)
44 {
45 Dad f = new Dad();
46 f.method();
47 Dad f1 = (Dad)new SmallSon();// 先初始化Dad(),然后再初始化SmallSon()
48 f1.method();//override smallson method
49 Dad f2 = (Dad)new BigSon();// 先初始化Dad(),然后再初始化Bigson()
50 f2.method();// Dad method
51 BigSon s = new BigSon();
52 s.method();
53
54 }
55 }
56 }
运行结果如下:
![](https://pic002.cnblogs.com/images/2011/276170/2011111810365858.jpg)
2.从输出结果可知:
第47行,先初始化基类再初始化子类构建器;
第48行,利用override重写了基类方法,得到的是子类方法;
第50行,利用new没有重写基类方法,得到的是基类方法;
第51、52行,输出子类方法结果。
所以,使用new没有用到基类方法,而是重新定义了子类方法,只不过方法名称与基类相同。