【问题标题】:Why can't I implement a default interface method in a class inheriting an abstract class that inherits that interface?为什么我不能在继承一个抽象类的类中实现一个默认的接口方法,这个抽象类继承了那个接口?
【发布时间】:2022-11-18 04:36:04
【问题描述】:

我有一个接口和一个继承这个接口的抽象类。

public interface ISomeInterface
{
    int Method()
    {
        return 1;
    }
}

public abstract class SomeAbstractClass : ISomeInterface {}

现在我想实现一个继承SomeAbstractClass 的类,它也将实现int Method()

public class SomeClass : SomeAbstractClass
{
    public int Method()
    {
        return 2;
    }
}

但是,当在转换为 ISomeInterfaceSomeClass 对象上调用 Method() 时,它将显示 1。

ISomeInterface someClass = new SomeClass();
Console.WriteLine($"{someClass.Method()}"); // displays 1

但是如果我将接口添加到SomeClass

public class SomeClass : SomeAbstractClass, ISomeInterface
{
    public int Method()
    {
        return 2;
    }
}

它会显示2。

为什么会这样?有什么方法可以通过从SomeAbstractClass继承来声明/实现Method(),而不需要写, ISomeInterface吗?

如果可能的话,我也不想修改SomeAbstractClass

我尝试在网上搜索解释,但是很难用简单的一句话来解释这个问题。我试图阅读更多关于默认接口方法的信息,但没有学到任何有意义的东西。

【问题讨论】:

    标签: c# inheritance


    【解决方案1】:

    正如您所注意到的,在SomeClass 中声明的Method 没有实现ISomeInterface.Method。你不能在SomeClass中实现ISomeInterface.Method,因为SomeAbstractClass已经完全实现了ISomeInterface

    通过不声明任何与ISomeInterface.Method 的签名相匹配的成员,SomeAbstractClass 通过“选择加入”Method 的默认实现来完全实现ISomeInterface

    这与抽象类通常的工作方式一致 - 如果 Method 没有默认实现,则空的 SomeAbstractClass 会导致编译器错误。如果你想SomeAbstractClass不是实现Method,并让它的具体子类来完成这项工作,您需要编写(无论Method是否有默认实现):

    public abstract int Method();
    

    Method 确实有默认实现时,这称为reabstraction

    情况有点像这样:

    // not actually how default interface members are implemented under the hood,
    // just for illustration purposes only
    public interface ISomeInterface
    {
        int Method();
    }
    
    public abstract class SomeAbstractClass : ISomeInterface {
    
        public int Method() => 1;
    }
    
    public class SomeClass : SomeAbstractClass
    {
        public int Method() => 2; // this method obviously does not implement ISomeInterface.Method!
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 2014-06-01
      • 2016-10-20
      • 2011-11-03
      • 2021-08-07
      • 2021-09-12
      • 2012-11-15
      • 2013-01-09
      • 1970-01-01
      相关资源
      最近更新 更多