c# - 我应该在继承链中包含所有接口(interface)吗?

标签 c# inheritance interface

如果我有两个接口(interface):

    interface IGrandparent
    {
        void DoSomething();
    }

    interface IParent : IGrandparent
    {
        void DoSomethingElse();
    }

那么有两种实现方式:

//only includes last interface from the inheritance chain
public class Child1 : IParent 
{
    public void DoSomething()
    {
        throw new NotImplementedException();
    }

    public void DoSomethingElse()
    {
        throw new NotImplementedException();
    }
}

// includes all the interfaces from the inheritance chain    
public class Child2 : IGrandparent, IParent     
{
    public void DoSomething()
    {
        throw new NotImplementedException();
    }

    public void DoSomethingElse()
    {
        throw new NotImplementedException();
    }
}

这两个实现是否相同? (类(class)名称除外)?有人说与“隐式和显式实现”有关,有人会解释为什么吗?我看到的 Child2 风格比另一个多。

最佳答案

隐式接口(interface)实现发生在不存在来自不同接口(interface)的冲突方法名称时,这是常见的情况。
另一方面,显式是指存在冲突的方法名称时,此时您必须指定方法中实现了哪个接口(interface)。

public interface IFoo
{
    void Do();   // conflicting name 1
}

public interface IBar
{
    void Do();   // conflicting name 2
}

public class FooBar : IFoo, IBar
{
    void IFoo.Do()    // explicit implementation 1
    {            
    }

    void IBar.Do()    // explicit implementation 1
    {
    }
}

请注意,显式实现的接口(interface)方法不能公开。 Here you can read more about explicit interface implementation.

谈论你的具体例子。您可以安全地只使用 IParent。即使您想使用明确的接口(interface)实现,您仍然可以在类声明中不特别提及 IGrandparent 来实现。

interface IGrandparent
{
    void DoSomething();
}

interface IParent : IGrandparent
{
    void DoSomethingElse();

    void DoSomething();
}

public class Child : IParent
{
    void IGrandparent.DoSomething()
    {
    }

    public void DoSomethingElse()
    {
    }

    public void DoSomething()
    {
    }
}

编辑:作为Dennis指出,还有其他几种使用显式接口(interface)实现的情况,包括接口(interface)重新实现。我在 here 中找到了关于隐式与显式接口(interface)实现用法的很好的推理。 (您可能还想查看整个线程,它很吸引人)。

关于c# - 我应该在继承链中包含所有接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705503/

相关文章:

pointers - 接口(interface)和地址运算符

c# - 从另一个线程更新控件的属性 (label.Text)

c# - C# 有没有办法将 "type"变为 long ?

Java 应用程序未将菜单打印到屏幕上

c# - 关于 C# 项目中神秘接口(interface)的警告

c# - 为什么这个方法调用不调用派生类?

c# - 如何在另一个类中使用扩展函数? C#

c# - EF Core 的 HasColumnName 发生了什么变化?

Java方法重载困惑

c# - 是否可以为不同的类型创建一个通用的抽象父类?