重新实现另一个接口已继承的接口
我经常看到这样的东西:
interface A { ... }
interface B : A { ... }
class C : B, A { ...}
当 B 已经继承了 A 时,为什么要指定 C 实现接口 A? 它是否有任何语义差异,或者只是风格问题?
(许多示例之一是 List
实现 IList
和 ICollection
,而 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信这只是风格问题。 在查看框架/库类时,这一点特别重要 - 例如,在您的示例中,它强调了此类可以被视为 ICollection 或 IList 的想法,而开发人员不必知道 IList 实际上是 ICollection。
它没有功能上的影响。 具体来说,这段代码是否会编译
类“C”显式实现“A”:
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: