思考这个问题一段时间后,我意识到静态鸭式语言实际上可能是可行的。为什么预定义类不能在编译时绑定到一个接口上呢?例如:
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并实现接口,或者使用适配器设计模式来实现相同的功能,但这些方法似乎只是不必要的样板代码。