【问题标题】:new vs override keywords新关键字 vs 覆盖关键字
【发布时间】:2014-03-25 23:35:05
【问题描述】:

我有一个关于多态方法的问题。我有两个类:具有非虚拟方法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
        }
    }

【问题讨论】:

    标签: c# polymorphism overriding


    【解决方案1】:

    (使用new时。)

    它甚至没有用到新的 Foo(int i) 方法。

    是的,但它执行Foo(int)BaseClass 实现,因为它在派生类中没有覆盖。这就是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)
    

    【讨论】:

    • 是不是像我们去基类调用虚方法,然后检查派生类是否包含重写方法,如果没有我们实现基虚方法?
    • @user3101007:嗯,有点。这不是“去”基本方法的问题 - 它只是找到该方法的最派生类型实现,而 new 启动一个 new 方法。
    【解决方案2】:

    您可能想看看这个: http://msdn.microsoft.com/en-us/library/ms173153.aspx

    开头如下:

    在 C# 中,派生类中的方法可以与方法同名 在基类中。您可以通过使用指定方法如何交互 new 和 override 关键字。 override 修饰符扩展了基础 类方法,并且 new 修饰符将其隐藏。不同的是 在本主题的示例中进行了说明。

    此行为是设计使然。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2019-06-11
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多