new 与override 区别

本文探讨了在C#中通过继承实现构造方法重写和使用new关键字隐藏基类成员的过程,通过实例展示了如何在派生类中初始化构造方法和重写方法,以及new关键字的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Newoverride
{
    class Dad
    {
        public Dad()
        {
            Console.WriteLine("Dad construtor");
        }
        public virtual void method()
        {
            Console.WriteLine("Dad method");
        }
    }
    class SmallSon : Dad
    {
        public SmallSon()
        {
            Console.WriteLine("Smallson construtor");
        }
        public override void method()
        {
            Console.WriteLine("override Smallson method");
        }
    }
    class BigSon : Dad
    {
        public BigSon()
        {
            Console.WriteLine("BigSon construtor");
        }
        public new void method()
        {
            Console.WriteLine("new BigSon method ");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Dad f = new Dad();
            f.method();
            Dad f1 = (Dad)new SmallSon();// 先初始化Dad(),然后再初始化SmallSon()
            f1.method();//override smallson method
            Dad f2 = (Dad)new BigSon();// 先初始化Dad(),然后再初始化Bigson()
            f2.method();// Dad method
            BigSon s = new BigSon();
            s.method();
           
        }
    }
}

 

 

2.从输出结果可知:
   第47行,先初始化基类再初始化子类构建器;
   第48行,利用override重写了基类方法,得到的是子类方法;
   第50行,利用new没有重写基类方法,得到的是基类方法;
   第51、52行,输出子类方法结果。
    所以,使用new没有用到基类方法,而是重新定义了子类方法,只不过方法名称与基类相同。
使用 new 修饰符显式隐藏从基类继承的成员。若要隐藏继承的成员,请使用相同名称在派生类中声明该成员,并用 new 修饰符修饰它。

转载于:https://www.cnblogs.com/wwwfj/p/3349285.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值