隐式与显式接口实现 [英] implicit vs explicit interface implementation

查看:23
本文介绍了隐式与显式接口实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
C#:接口 - 隐式和显式实现

谁能解释一下这两种野兽之间的区别以及如何使用它们.AFAIK,许多 pre.2.0 类是在没有泛型类型的情况下实现的,因此导致后一个版本实现了两种风格的接口.是唯一需要使用它们的情况吗?

Would someone explain the differences between these two beasts and how to use them. AFAIK, many pre.2.0 classes were implemented without generic types, thus causing latter version to implement both flavors of interfaces. Is the the only case why one would need to use them?

您能否也深入解释一下如何使用它们.?

Can you also explain in depth how to use them.?

谢谢

推荐答案

有一篇关于此的很好且非常详细的博客文章.

基本上,通过隐式接口实现,您可以访问接口方法和属性,就好像它们是类的一部分一样.使用显式接口实现,您只能在将其视为该接口时才能访问它们.

Basically with implicit interface implementation you access the interface methods and properties as if they were part of the class. With explicit interface implementations you can only access them when treating it as that interface.

就何时使用一个而不是另一个而言,有时您必须使用显式接口实现,因为您要么拥有与接口具有相同签名的属性/方法,要么想要实现具有相同签名的两个接口并具有匹配的属性/方法的不同实现.

In terms of when you would use one over the other, sometimes you have to use explicit interface implementation as you either have a property/method with same signature as the interface or you want to implement two interfaces with the same signatures and have different implementations for those properties/methods that match.

以下规则来自 Brad Abrams 设计指南博客.

The below rules are from Brad Abrams design guidelines blog.

  • 不要使用显式成员作为安全边界.任何将实例转换为接口的客户端都可以调用它们.
  • 务必使用显式成员来隐藏实现细节
  • 务必使用显式成员来近似私有接口实现.
  • 公开一种替代方法来访问允许子类覆盖的任何显式实现的成员.除非出现冲突,否则请使用相同的方法名称.
  • Do not use explicit members as a security boundary. They can be called by any client who cast an instance to the interface.
  • Do use explicit members to hide implementation details
  • Do use explicit members to approximate private interface implementations.
  • Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override. Use the same method name unless a conflict would arise.

Brad 博客的评论中还提到,在值类型上使用显式实现时会涉及装箱,因此请注意性能成本.

It's also mentioned in the comments in Brad's blog that there is boxing involved when using explicit implementation on value types so be aware of the performance cost.

这篇关于隐式与显式接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆