问题描述
想知道以下之间有什么区别:
Wondering what the difference is between the following:
案例 1:基类
public void DoIt();
案例一:继承类
public new void DoIt();
案例 2:基类
public virtual void DoIt();
案例2:继承类
public override void DoIt();
根据我运行的测试,案例 1 和 2 似乎具有相同的效果.有区别,还是首选方式?
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
如果覆盖 Base.DoIt
,将调用 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
将首先调用 Base.DoIt
,然后是 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.
来源:微软博客
这篇关于新建和覆盖之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!