还有哪些语言允许程序员使用接口作为函数参数?
让我解释一下:
我知道,在 Java 中,你可以做这样的事情:
int myMethod(Burnable obj){
/*do stuff that's only applicable if the argument implements the Burnable
*interface
*/
}
我最喜欢用 PHP 编程,而且我不确定 是否我也可以用 PHP 做到这一点。
此外,我想知道还有哪些其他相当主流语言具有此功能,因为在我看来,这是在代码中构建模块化的一种方式。
谢谢
Let me explain:
I know that, in Java, you can do stuff like this:
int myMethod(Burnable obj){
/*do stuff that's only applicable if the argument implements the Burnable
*interface
*/
}
I like programming in PHP the most, and I'm not sure whether I can do that in PHP too.
Furthermore, I'd like to know what other reasonably mainstream languages that feature this, as in my view it's a way of building modularity into your code.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
所有静态类型语言(C、C++、Java、Objective-C、Ada 和许多其他语言)都允许指定函数参数的类型。其中的一个子集允许重载(具有多个具有相同名称但具有不同类型参数的不同函数)。从 PHP5 开始,可以使用 类型提示 指定参数类型验证函数调用是否传递预期类型的参数;但是,PHP 不支持重载(尽管您可以使函数接受多种不同类型,然后检查类型并按类型分派到不同的实现)。
All statically-typed languages (C, C++, Java, Objective-C, Ada, and many others) allow one to specify the types of a function's parameters. A subset of them allow for overloading (having multiple different functions with the same name but with different typed parameters). Since PHP5, it is possible to specify the types of parameters using type hinting to validate that function calls pass parameters of the expected type; however, PHP does not support overloading (although you can make functions accept multiple different types, and then check the types and dispatch to different implementations by type).
所有标准 CLR 语言(C#、VB.NET、F#)都支持使用接口。 Haskell 有提供类似功能的类型类。
All the standard CLR languages (C#, VB.NET, F#) support using interfaces. Haskell has typeclasses which serve a similar function.
每个面向对象的语言都允许这样做。它们的不同之处在于“interface”的拼写方式。在 C++ 中,它只是一种特殊类型的类,其中每个成员都是“纯虚拟”(现在称为“抽象”)。在 C# 中它就像 java 一样。在动态类型语言中,例如 PHP、Python 和 Ruby,它只是隐式的(即参数必须符合的接口没有明确说明,但抽象中仍然存在一个“接口”)。
做到这一点的能力与里氏替换原理有关,它是面向对象编程的基本原则之一。很高兴你喜欢它:-)
Every object-oriented language allows this. They differ in how they spell "interface". In C++ it is just a particular kind of class, where every member is "pure virtual" (now known as "abstract"). In C# it's just like java. In the dynamically-typed languages, PHP, Python, and Ruby for example, it is just implicit (i.e. the interface to which the argument must conform is not spelled out explicitly, but there still is an "interface" in the abstract).
The ability to do this is related to the Liskov substitution principle, and it is one of the fundamental tenets of object-oriented programming. Glad you like it :-)