且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能拥有受保护的接口成员?

更新时间:2022-01-13 00:17:58

我想每个人都认为接口只有公共成员,没有实现细节.您正在寻找的是抽象类.

I think everyone hammered the point of an interface having only public members, no implementation details. What you are looking for is an abstract class.

public interface IOrange
{
    OrangePeel Peel { get; }
}

public abstract class OrangeBase : IOrange
{
    protected OrangeBase() {}
    protected abstract OrangePips Seeds { get; }
    public abstract OrangePeel Peel { get; }
}

public class NavelOrange : OrangeBase
{
    public override OrangePeel Peel { get { return new OrangePeel(); } }
    protected override OrangePips Seeds { get { return null; } }
}

public class ValenciaOrange : OrangeBase
{
    public override OrangePeel Peel { get { return new OrangePeel(); } }
    protected override OrangePips Seeds { get { return new OrangePips(6); } }
}

公平地说,如果我们有一个派生自 Ornament 类的 PlasticOrange,它只能实现 IOrange 而不能实现 Seeds 保护的方法.没事儿.根据定义,接口是调用者和对象之间的契约,而不是类与其子类之间的契约.抽象类与我们接近这个概念.这很好.您本质上提出的是语言中的另一种构造,通过它我们可以将子类从一个基类切换到另一个基类,而不会破坏构建.对我来说,这没有意义.

It is fair to argue that if we have a PlasticOrange that derives from a class Ornament, it can only implement IOrange and not the Seeds protected method. That is fine. An interface by definition is a contract between a caller and an object, not between a class and its subclasses. The abstract class is as close as we come to this concept. And that is fine. What you are essentially proposing is another construct in the language through which we can switch subclasses from one base class to another without breaking the build. To me, this doesn't make sense.

如果您要创建类的子类,则子类是基类的特化.它应该完全了解基类的任何受保护成员.但是如果你突然想把基类切换出去,那么子类应该与任何其他 IOrange 一起工作是没有意义的.

If you are creating a subclass of a class, the subclass is a specialization of the base class. It should be fully aware of any protected members of the base class. But if you suddenly want to switch the base class out, it makes no sense that the subclass should work with any other IOrange.

我想你有一个公平的问题,但它似乎是一个极端案例,老实说,我认为它没有任何好处.

I suppose you have a fair question, but it seems like a corner case and I don't see any benefit from it to be honest.