【问题标题】:Child classes with the same interface as base class with the new key word与基类具有相同接口的子类具有新的关键字
【发布时间】:2018-06-15 13:06:34
【问题描述】:

我试图理解为什么它的行为如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstarctWithInterfcae
{  
public interface IBase
{
    void Display();
}

public abstract class Base : IBase
{        
    public void Display()
    {
        Console.WriteLine("Base Display");
    }
}


public class child1 : Base, IBase
{
    public new void Display()
    {
        Console.WriteLine("child1 Display");
    }
}

public class child2 : Base,IBase
{     
    public new void Display()
    {
        Console.WriteLine("child2 Display");
    }
}

class Program
{
    static void Main(string[] args)
    {
        IBase obj = new child1();
        obj.Display(); // writing child1 display
        IBase obj2 = new child2();
        obj.Display(); //Wrirting child1 dispaly
        Console.ReadLine();
    }
}
}

第一个问题:

在上面的程序中,我使用 new 它应该调用基类方法 为什么会这样 调用 Child 1 Display

据我了解,我们有已经实现 IBase 的基类,因此当我们通过引用接口为 child1 创建实例时,它应该调用基类方法,因为它继承了基类并具有新的关键字。

如果有人给出解释,将不胜感激

【问题讨论】:

  • 在第二种情况下(ReadLine 之前)你不是说obj2.Display() 吗?
  • Display的基本定义是否应该是Virtual,然后子实现可以覆盖基本定义而不是隐藏它?
  • @vc74 是的。我做错了:)。现在我明白了

标签: c# oop


【解决方案1】:

您在这里看到的是界面重新实现。在第一种情况下,基类是实现接口的最派生类,因此它将接口的方法绑定到它的方法实现。由于该方法不是虚拟的,因此它不能也不会被覆盖,因此当您在基类或派生类上使用接口时,就会调用该方法。

在第二个示例中,您在派生类上重新实现了接口(通过将其添加到类的声明中)。这会重新绑定接口的方法使用该类型。因为它有一个合适的方法,所以只要接口用于派生类型的方法,就会使用它的实现。

【讨论】:

    【解决方案2】:

    场景 1 是因为您使用的是 obj.Display() 而不是 obj2.Display()

    场景 2 是因为您使用通用接口引用 IBase, (IBase obj = new child2()) 并且 C# 将选择最不复杂的类型以适应实际对象类型,因为它假定您要在“最少类型的特定版本',因为您不是特定的。

    编辑:注意到反对票,我假设有人认为这个答案不够完整;

    如果 OP 希望正确查看错误 2 的输出,他们可以将类型实例化为 Child2 obj = new Child2();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      相关资源
      最近更新 更多