新覆盖的区别 [英] Difference between new and override
问题描述
想知道有什么区别以下的:
案例1:基地班
公共无效DOIT();
案例1:继承的类
公开新DOIT无效();
案例2:基地班
公共虚拟无效DOIT();
案例2:继承的类
公共覆盖无效DOIT();
两个壳体1和2看起来有基于我已进行的测试相同的效果。是否有区别,或者preferred方式?
的倍率改性剂可被用于在
虚拟方法和必须使用上
抽象方法。这表明了
编译器使用最后定义
实现的方法。即使
该方法被称为上的基准
基类它将使用
实现覆盖它。
块引用>公共类基地
{
公共虚拟无效DOIT()
{
}
}公共类派生:基地
{
公共覆盖无效DOIT()
{
}
}基地B =新派生的();
b.DoIt(); //调用Derived.DoIt将调用Derived.DoIt如果覆盖Base.DoIt。
new修饰符指示
编译器使用您的孩子类实现
代替父类
实现。任何code,是不是
引用您的类,但父
类将使用父类
实施
块引用>公共类基地
{
公共虚拟无效DOIT()
{
}
}公共类派生:基地
{
新公共DOIT无效()
{
}
}基地B =新派生的();
衍生D =新的派生();b.DoIt(); //调用Base.DoIt
d.DoIt(); //调用Derived.DoIt首先会调用Base.DoIt,然后Derived.DoIt。他们恰巧有相同的名称,而不是派生的方法重写基方法有效地两个完全不同的方法。
来源:<一个href=\"http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-s-the-difference-between-$c$c-override-$c$c-and-$c$c-new-$c$c.aspx\">Microsoft博客
Wondering what the difference is between the following:
Case 1: Base Class
public void DoIt();
Case 1: Inherited class
public new void DoIt();
Case 2: Base Class
public virtual void DoIt();
Case 2: Inherited class
public override void DoIt();
Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?
解决方案The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.
public class Base { public virtual void DoIt() { } } public class Derived : Base { public override void DoIt() { } } Base b = new Derived(); b.DoIt(); // Calls Derived.DoIt
will call Derived.DoIt if that overrides Base.DoIt.
The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation. Any code that is not referencing your class but the parent class will use the parent class implementation.
public class Base { public virtual void DoIt() { } } public class Derived : Base { public new void DoIt() { } } Base b = new Derived(); Derived d = new Derived(); b.DoIt(); // Calls Base.DoIt d.DoIt(); // Calls Derived.DoIt
Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
Source: Microsoft blog
这篇关于新覆盖的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!