C# 和接口 - 显式与隐式
在 C# 中,如果一个类具有接口的所有正确方法/签名,但没有显式实现它,例如:
class foo : IDoo {}
该类是否仍可以转换为该接口?
In C#, if a class has all the correct methods/signatures for an Interface, but doesn't explicitly implement it like:
class foo : IDoo {}
Can the class still be cast as that interface?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
鸭子打字
您所提到的被称为“鸭子打字”(得名于成语“如果它看起来像鸭子,并且嘎嘎叫像鸭子,那么它一定是鸭子”)。
对于鸭子类型,一旦您实现了相关成员(正如您所描述的),接口实现就是隐式的,但是 .NET 目前对此没有任何广泛的支持。
考虑到未来计划出现的新兴动态语言功能,如果运行时在不久的将来原生支持这一功能,我不会感到惊讶。
同时,您可以通过反射综合鸭子类型,使用 a像这样的库,它允许您执行如下所示的鸭子类型转换:
IDoo myDoo = DuckTyping.Cast(myFoo)
Some Trivia
有趣的是,如今 C# 中有一个小地方使用了鸭子类型 -
foreach
运算符。 Krzysztof Cwalina 声明为了可枚举对于foreach
运算符,类必须:请注意,他没有提及
IEnumerable
也没有提及IEnumerator
。 尽管在创建可枚举类时实现这些接口很常见,但如果您要删除这些接口但保留实现,您的类仍然可以通过foreach
进行枚举。 瞧! 鸭子打字! (示例代码。)Duck Typing
What you are alluding to is referred to as "duck-typing" (named after the idiom "if it looks like a duck, and quacks like a duck, then it must be a duck").
With duck-typing an interface implementation is implicit once you have implemented the relevant members (just as you describe) however .NET does not currently have any broad support for this.
With the emergent dynamic language features planned for the future, I wouldn't be surprised if this were supported natively by the runtime in the near future.
In the mean time, you can synthesise duck-typing via reflection, with a library such as this, which would allow you to do a duck-typed cast like this:
IDoo myDoo = DuckTyping.Cast<IDoo>(myFoo)
Some Trivia
Interestingly, there is one small place where duck-typing is in use in C# today — the
foreach
operator. Krzysztof Cwalina states that in order to be enumerable by theforeach
operator, a class must:Notice that he makes no mention of
IEnumerable
norIEnumerator
. Although it is common to implement these interfaces when creating an enumerable class, if you were to drop the interfaces but leave the implementation, your class would still be enumerable byforeach
. Voila! Duck-typing! (Example code here.)不,它不像 Objective-C 和其他一些语言。 您应该显式声明接口实现。
No, it's not like Objective-C and some other languages. You should explicitly declare interface implementation.
如果 IDoo 有任何成员,则此代码将无法编译。 如果 IDoo 没有成员,那么是的,演员阵容是安全的(但显然用途有限)。
Provided that IDoo has any members, this code won't compile. If IDoo has no members, then yes, the cast is safe (but obviously of limited use).
这基本上需要 Duck Typing 在 C# 中工作,但这不会自动发生。
有一些库可以做到这一点, 尽管。
This would basically require Duck Typing to work in C#, which does not happen automatically.
There are some libraries that can do this, though.
B 通过继承 A 满足 IDoSomething.DoSomething
B satisfies IDoSomething.DoSomething by inheriting from A