有没有静态鸭子类型的语言? [英] Are there any static duck-typed languages?

查看:29
本文介绍了有没有静态鸭子类型的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在声明成员时指定接口吗?

在思考这个问题一段时间后,我突然想到静态鸭子类型的语言可能真的有效.为什么不能在编译时将预定义的类绑定到接口?示例:

After thinking about this question for a while, it occurred to me that a static-duck-typed language might actually work. Why can't predefined classes be bound to an interface at compile time? Example:

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 并实现接口或使用适配器设计模式来完成相同的事情,但这些方法似乎只是不必要的样板代码.

Do you know of any languages that support such a feature? Would it be helpful in Java or C#? Is it fundamentally flawed in some way? I understand you could subclass MyClass and implement the interface or use the Adapter design pattern to accomplish the same thing, but those approaches just seem like unnecessary boilerplate code.

推荐答案

根据定义,静态类型语言在编译时而不是运行时检查类型.上述系统的一个明显问题是编译器将在编译程序时而不是在运行时检查类型.

Statically-typed languages, by definition, check types at compile time, not run time. One of the obvious problems with the system described above is that the compiler is going to check types when the program is compiled, not at run time.

现在,您可以在编译器中构建更多智能,以便它可以派生类型,而不是让程序员显式声明类型;编译器可能会看到 MyClass 实现了一个 MyMethod() 方法,并相应地处理这种情况, 无需显式声明接口(如你所建议).这样的编译器可以利用类型推断,例如 Hindley-Milner.

Now, you could build more intelligence into the compiler so it could derive types, rather than having the programmer explicitly declare types; the compiler might be able to see that MyClass implements a MyMethod() method, and handle this case accordingly, without the need to explicitly declare interfaces (as you suggest). Such a compiler could utilize type inference, such as Hindley-Milner.

当然,一些像 Haskell 这样的静态类型语言已经做了一些类似的事情;Haskell 编译器能够推断类型(大多数情况下)而无需显式声明它们.但是很明显,Java/C#没有这个能力.

Of course, some statically typed languages like Haskell already do something similar to what you suggest; the Haskell compiler is able to infer types (most of the time) without the need to explicitly declare them. But obviously, Java/C# don't have this ability.

这篇关于有没有静态鸭子类型的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆