c# - 在 C# 中实现安全的鸭子类型(duck typing)

标签 c# adapter duck-typing

看了之后如何Go处理接口(interface)并喜欢它,我开始考虑如何在 C# 中实现类似的 duck-typing,如下所示:

var mallard = new Mallard(); // doesn't implement IDuck but has the right methods
IDuck duck = DuckTyper.Adapt<Mallard,IDuck>(mallard);

DuckTyper.Adapt 方法将使用 System.Reflection.Emit 动态构建适配器。也许有人已经写过这样的东西。我想这与模拟框架已经做的并没有太大不同。

但是,如果 Mallard 实际上没有正确的 IDuck 方法,这将在运行时抛出异常。为了在编译时尽早发现错误,我必须编写一个 MallardToDuckAdapter,这正是我要避免的。

有没有更好的办法?

编辑:显然我所说的“安全鸭子类型(duck typing)”的正确术语是 structural typing .

最佳答案

如果你面前没有一头活生生、会呼吸的牛,你怎么知道一头牛是不是像鸭子类型(duck typing)一样走路,是否像鸭子类型(duck typing)一样嘎嘎叫?

Duck-typing 是一个在运行时使用的概念。编译时的类似概念是 structural typing CLR 不支持 AFAIK。 (CLR 以 nominative typing 为中心。)

[A structural type system] contrasts with nominative systems, where comparisons are based on explicit declarations or the names of the types, and duck typing, in which only the part of the structure accessed at runtime is checked for compatibility.

确保鸭子类型(duck typing)在运行时不抛出异常的常用方法是单元测试。

关于c# - 在 C# 中实现安全的鸭子类型(duck typing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1730711/

相关文章:

android - ListActivity的onListItemClick不起作用

Android - notifyDataSetChanged() 不适用于自定义适配器?

python - 如何仅键入协议(protocol)方法的第一个位置参数并让其他参数不键入?

delphi - 在 Delphi 2007 中鸭子类型(duck typing)?

c# - 删除 Application Insights 后应用程序将无法启动

c# - 将 C 结构编码到 C#

c# - 选择 HTML.RadioButtonFor 后如何为模型属性赋值

c# - 如何获得不同的列表类型列表

android - 通过另一个适配器访问一个适配器的数据

javascript - 让 instanceof 运算符与 JavaScript 中的多个父类(super class)一起使用