新vs覆盖关键字

use*_*007 1 c# polymorphism overriding

我有一个关于多态方法的问题.我有两个类:带有非虚方法的基类,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
    }
}
Run Code Online (Sandbox Code Playgroud)

////////////////////////////////////////////////// ////////////////////

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
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

(使用时new.)

它甚至没有达到新的Foo(int i)方法.

是的确如此 - 但它执行的BaseClassFoo(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)
Run Code Online (Sandbox Code Playgroud)

但使用时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)
Run Code Online (Sandbox Code Playgroud)