没有办法定义具有特定功能的结构类型。有一个为 C# 添加鸭子类型支持的库,可以在此处找到。
这是 Duck Typing 项目的示例。请注意,鸭子输入发生在运行时并且可能会失败。我的理解也是,这个库为鸭子类型的类型生成代理,这与 Scala 中所享有的优雅的编译时支持相去甚远。这很可能与这一代 C# 一样好。
public interface ICanAdd
{
int Add(int x, int y);
}
// Note that MyAdder does NOT implement ICanAdd,
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
public int Add(int x, int y)
{
return x + y;
}
}
public class Program
{
void Main()
{
MyAdder myAdder = new MyAdder();
// Even though ICanAdd is not implemented by MyAdder,
// we can duck cast it because it implements all the members:
ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);
// Now we can call adder as you would any ICanAdd object.
// Transparently, this call is being forwarded to myAdder.
int sum = adder.Add(2, 2);
}
}
这是使用良好的 ol 无聊接口实现相同目标的 C# 方式。
interface IPressable {
void Press();
}
class Foo {
void Bar(IPressable pressable) {
pressable.Press();
}
}
class Thingy : IPressable, IPushable, etc {
public void Press() {
}
}
static class Program {
public static void Main() {
pressable = new Thingy();
new Foo().Bar(pressable);
}
}