c# - 具有与具有新关键字的基类相同接口(interface)的子类

标签 c# oop

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

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 的基类,因此当我们通过引用接口(interface)为 child1 创建实例时,它应该调用基类方法,因为它继承了基类并具有新的关键字。

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

最佳答案

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

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

关于c# - 具有与具有新关键字的基类相同接口(interface)的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876268/

相关文章:

c# - 禁用 ComboBox C# 中的项目

c# - 动态添加面板c#

c# - 将接口(interface)传递给 ASP.NET MVC Controller Action 方法

class - 使用类的 Common Lisp 替代方案

c# - 正则表达式替换多个新行

c# - 无效泛型类型参数的最佳异常(exception)

c# - 来自 Resource.Designer.cs 的模糊引用智能感知错误

php - 工厂设计模式实现疑惑

c++ - C++ 中的对象内存布局及其结构如何依赖于大多数平台

Javascript:具有相同值的对象数组的每个元素