new和override的区别

MSDN:

It is an error to use both new and override on the same member because the two modifiers have mutually exclusive meanings.The new modifiers creates a new member with the same name and causes the original menber to become hidden.The override modifier extends the implementation for an inherited member.

 

This is all to do with polymorphism.When a virtual method is called on a referrence,the actual type of the object that the teference refers to is used to decide which method implementation to use.When a method of a base class is overriden in a derived class,the version in the derived class is used,even if the calling code didn't "know" that the object was an instance of the derived class.For instance:

public class Base
{
    public virtual void SomeMethod()
    {
    }
}

public class Derived : Base
{
    public override void SomeMethod()
    {
    }
}

...

Base b = new Derived();
b.SomeMethod();

will end up calling Derived.SomeMethod if that overrides Base.SomeMethod. Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:

public class Base
{
    public virtual void SomeOtherMethod()
    {
    }
}

public class Derived : Base
{
    public new void SomeOtherMethod()
    {
    }
}

...

Base b = new Derived();
Derived d = new Derived();
b.SomeOtherMethod();
d.SomeOtherMethod();

Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4). They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.

If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).

That provides the basics of overriding and the difference between new and override, but you should really see a book or tutorial for a more in-depth look at polymorphism.

[Author: Jon Skeet]

 

(先看实现上的签名签名,然后看继承上的override, 剩下的是new.默认new.这和接口映射先看显式接口成员执行体,再非静态的公有成员,然后基类类使)

转载于:https://www.cnblogs.com/szjdw/archive/2012/03/19/2406867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值