c# - 新vs覆盖关键字

标签 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
    }
}


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

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)方法。


是的,它确实可以,但是它执行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)


但是当使用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/

相关文章:

c# - 多态和类型转换

c++ - 覆盖 - 如何用更少的打字来做到这一点?

c# - 无法转换作为派生类的继承类字段

c# - 为什么 STL 中的 set_intersection 这么慢?

C# 有 foreach oneliner 可用吗?

c# - 如何在设计时在 .net 和 winforms 中向图书馆的最终用户提供应用程序设置

C++ 接口(interface)、继承、多态性

c# - 新的C#异步功能的一个很好的非联网示例是什么?

java - 有没有办法在 Java 中使用单个对象来运行继承的其他类的方法?

java - "safely"如何使用通用模板的多态性?