我有一个关于多态方法的问题。我有两个类:具有非虚拟方法Foo( )
的基类,该方法调用其虚拟方法Foo (int i)
(例如:Foo() {Foo(1);})
)和派生类,其覆盖方法Foo(int i)
。
如果我调用派生类实例的Foo()
方法,则演练如下:base Foo() -> override Foo(int i)
。但是,如果我将替代方法更改为新方法,则演练如下:base Foo -> base Foo(int i)
。它甚至没有涉及到新的Foo(int i)
方法。请解释这些方法的顺序以及为什么会这样。
using System;
class Program
{
sealed void Main()
{
DerivedClass d = new DerivedClass();
//Goes to BaseClass Foo() method
//then goes to Derived Foo(int i ) method
d.Foo();
}
}
class BaseClass
{
public void Foo() { Foo(1); }
public virtual void Foo(int i) { // do something;
}
}
class DerivedClass : BaseClass
{
public override void Foo(int i) { //Do something
}
}
///////////////////////////////////////////////////// ////////////////////
using System;
class Program
{
sealed void Main()
{
DerivedClass d = new DerivedClass();
//Goes to BaseClass Foo() method
//then goes to base Foo(int i) method
//never gets to Foo(int i) of the derived class
d.Foo();
}
}
class BaseClass
{
public void Foo() { Foo(1); }
public virtual void Foo(int i) { // do something;
}
}
class DerivedClass : BaseClass
{
public new void Foo(int i) { //Do something
}
}
最佳答案
(使用new
时。)
它甚至没有涉及到新的Foo(int i)方法。
是的,它确实可以,但是它执行BaseClass
的Foo(int)
实现,因为在派生类中未重写该实现。这就是new
的全部要点-就是说,“我没有重写基类方法-我是一个全新的方法。”如果要覆盖基类方法,请使用override
。线索在关键字中:)
因此,例如,使用new
时:
BaseClass x = new DerivedClass();
x.Foo(1); // Calls BaseClass.Foo(int)
DerivedClass y = new DerivedClass();
y.Foo(1); // Calls DerivedClass.Foo(int)
但是当使用
override
时:BaseClass x = new DerivedClass();
x.Foo(1); // Calls DerivedClass.Foo(int) // Due to overriding
DerivedClass y = new DerivedClass();
y.Foo(1); // Calls DerivedClass.Foo(int)
关于c# - 新vs覆盖关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577383/