• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一蓑烟雨
C/C++,Linux,语音技术
博客园    首页    新随笔    联系   管理    订阅  订阅
new和override区别

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 }

运行结果如下:

2.从输出结果可知:
   第47行,先初始化基类再初始化子类构建器;
   第48行,利用override重写了基类方法,得到的是子类方法;
   第50行,利用new没有重写基类方法,得到的是基类方法;
   第51、52行,输出子类方法结果。
   所以,使用new没有用到基类方法,而是重新定义了子类方法,只不过方法名称与基类相同。
posted on 2011-11-18 10:47  lovemu  阅读(1220)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3