C# 和接口(interface) - 显式与隐式

标签 c# .net interface casting duck-typing

在 C# 中,如果一个类具有接口(interface)的所有正确方法/签名,但没有显式实现它,例如:

class foo : IDoo {}

类仍然可以转换为该接口(interface)吗?

最佳答案

鸭子类型(duck typing)

您所指的是“duck-typing”(以成语“长得像鸭子类型(duck typing),叫起来像鸭子类型(duck typing),那一定是鸭子类型(duck typing)”命名)。

一旦您实现了相关成员(正如您所描述的),使用鸭子类型(duck typing)接口(interface)实现是隐式的,但是 .NET 目前对此没有任何广泛的支持。

随着为 future 计划的新兴动态语言功能,如果在不久的将来运行时本地支持它,我不会感到惊讶。

与此同时,您可以通过反射合成鸭子类型(duck typing),使用 a library such as this ,这将允许您像这样进行鸭子类型(duck typing)的转换:IDoo myDoo = DuckTyping.Cast<IDoo>(myFoo)

一些琐事

有趣的是,今天在 C# 中有一个小地方使用鸭子类型(duck typing) — foreach运算符(operator)。 Krzysztof Cwalina states为了能够被 foreach 枚举运算符,一个类必须:

Provide a public method GetEnumerator that takes no parameters and returns a type that has two members: a) a method MoveMext that takes no parameters and return a Boolean, and b) a property Current with a getter that returns an Object.

注意他没有提到 IEnumerable也不IEnumerator .尽管在创建可枚举类时实现这些接口(interface)很常见,但如果您要删除接口(interface)但保留实现,您的类仍可被 foreach 枚举。 .瞧!鸭子类型(duck typing)! ( Example code here .)

关于C# 和接口(interface) - 显式与隐式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/787525/

相关文章:

c# - 绑定(bind) DataTemplate 中的 RotateTransform Angle 未生效

c# - 动态调整数组大小

c# - CompareTo 如何对列表进行排序?

c# - 指定函数参数的类型*和*接口(interface)

vb.net - 如何在 vb 通用接口(interface)中创建一个返回实现类实例的方法?

interface - 任意接口(interface)列表中哪些接口(interface)满足?

c# - 如何在 C# 中从 api 解析奇怪的 json 对象

c# - 如果键不存在,C# Dictionary<int, int> 查找会发生什么情况?

c# - AmazonCloudWatchLogsClient 异步方法失败但没有错误

jquery - 更改库 graphdracula 中的字体大小