【发布时间】:2010-09-22 07:00:48
【问题描述】:
Can I specify interfaces when I declare a member?
在考虑了这个问题一段时间后,我突然想到静态鸭子类型的语言可能真的有效。为什么预定义的类不能在编译时绑定到接口?示例:
public interface IMyInterface
{
public void MyMethod();
}
public class MyClass //Does not explicitly implement IMyInterface
{
public void MyMethod() //But contains a compatible method definition
{
Console.WriteLine("Hello, world!");
}
}
...
public void CallMyMethod(IMyInterface m)
{
m.MyMethod();
}
...
MyClass obj = new MyClass();
CallMyMethod(obj); // Automatically recognize that MyClass "fits"
// MyInterface, and force a type-cast.
您知道支持这种功能的任何语言吗?它对 Java 或 C# 有帮助吗?它在某些方面存在根本缺陷吗?我知道你可以继承 MyClass 并实现接口或使用适配器设计模式来完成同样的事情,但这些方法看起来像是不必要的样板代码。
【问题讨论】:
标签: class interface language-design duck-typing static-typing