重新实现另一个接口已继承的接口

发布于 2024-07-08 22:26:44 字数 656 浏览 5 评论 0原文

我经常看到这样的东西:

interface A { ... }
interface B : A { ... }
class C : B, A { ...}

当 B 已经继承了 A 时,为什么要指定 C 实现接口 A? 它是否有任何语义差异,或者只是风格问题?

(许多示例之一是 List 实现 IListICollection,而 IList< ;T> 也源自 ICollection)。


更新: 感谢您证实我的猜测,它不会产生任何语义差异。

我提出了一个相关的情况,显式命名继承树中已有的接口确实会产生影响:

如果B是一个类,如果 C 在“:”之后显式命名 A,则它只会(重新)实现 A 中的接口成员。

[编辑]我更改了问题的措辞,以避免与显式实现的接口成员混淆,这将成员的使用限制为将对象强制转换为接口的情况。

I see stuff like this a lot:

interface A { ... }
interface B : A { ... }
class C : B, A { ...}

Why would you specify that C implements interface A, when B already inherits A?
Does it make any semantic difference or is it just a matter of style?

(One of many examples is List<T> implementing IList<T> and ICollection<T>, while IList<T> also derives from ICollection<T>).


Update: Thanks for confirming my guess that it doesn't make any semantic difference.

I have come up with a related situation where it does make a difference to explicitly name an interface that is already in the inheritance tree:

If B were a class, C would only (re-)implement interface members from A if it names A explicitly after the ':'.

[EDIT] I changed the wording of the question to avoid confusion with explicitly implemented interface members, which restrict the use of the member to cases where the object is cast as the interface.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

土豪 2024-07-15 22:26:45

我相信这只是风格问题。 在查看框架/库类时,这一点特别重要 - 例如,在您的示例中,它强调了此类可以被视为 ICollection 或 IList 的想法,而开发人员不必知道 IList 实际上是 ICollection。

它没有功能上的影响。 具体来说,这段代码是否会编译
类“C”显式实现“A”:

namespace DotNetInterfaceTest {
    class Program {
        static void Main(string[] args) {
            A c = new C();
        }
    }

    interface A {
        void foo();
    }

    interface B : A {
        void bar();
    }

    class C : B {
        public void bar() {}
        public void foo() {}
    }
}

I believe this is just a matter of style. It is specifically important when looking at framework/library classes - in your example, for instance, it highlights the idea that this class can be treated as either an ICollection or an IList, without the developer having to know that IList is actually an ICollection.

It has no functional ramifications. Specifically, this code would compile whether or not
class 'C' implements 'A' explicitly:

namespace DotNetInterfaceTest {
    class Program {
        static void Main(string[] args) {
            A c = new C();
        }
    }

    interface A {
        void foo();
    }

    interface B : A {
        void bar();
    }

    class C : B {
        public void bar() {}
        public void foo() {}
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文