C# new 和 orverride 区别

主要还是参考微软的说明,原文:http://msdn.microsoft.com/zh-cn/library/ms173153.aspx


以下是我的理解:

一、BaseClass(父类、基类):

  • orverride BaseClass 中的方法必须声明为 virtual,否则会出现编译错误;
  • new BaseClass 中的方法声明或不声明为 virtual 均可

二、ChildClass(子类)

  • orverride ChildClass 中的方法必须声明为 orverride,否则会出现编译错误;
  • new BaseClass 中的方法声明或不声明为 new 均可

大部分情况下,new 和 orverride 处理逻辑是一致的,即调用子类的方法。唯独在 “多态” 这种情况:

BaseClass item = new DerivedClass();

item 调用方法时,如果子类中的方法是用 new 声明的,会调用基类的方法,但如果是 orverride 声明的,则会调用子类的方法,这应该是正确的效果。


微软的例子很经典:

using System;
using System.Text;

namespace OverrideAndNew
{

    class BaseClass
    {
        public virtual void Method1()
        {
            Console.WriteLine("Base - Method1");
        }

        public virtual void Method2()
        {
            Console.WriteLine("Base - Method2");
        }
    }

    class DerivedClass : BaseClass
    {
        public override void Method1()
        {
            Console.WriteLine("Derived - Method1");
        }

        public new void Method2()
        {
            Console.WriteLine("Derived - Method2");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new BaseClass();
            DerivedClass dc = new DerivedClass();
            BaseClass bcdc = new DerivedClass();

            // The following two calls do what you would expect. They call
            // the methods that are defined in BaseClass.
            bc.Method1();
            bc.Method2();
            // Output:
            // Base - Method1
            // Base - Method2


            // The following two calls do what you would expect. They call
            // the methods that are defined in DerivedClass.
            dc.Method1();
            dc.Method2();
            // Output:
            // Derived - Method1
            // Derived - Method2


            // The following two calls produce different results, depending 
            // on whether override (Method1) or new (Method2) is used.
            bcdc.Method1();
            bcdc.Method2();
            // Output:
            // Derived - Method1
            // Base - Method2
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值