C#有一个相当于Scala的结构性打字? [英] Does C# have an equivalent to Scala's structural typing?

查看:129
本文介绍了C#有一个相当于Scala的结构性打字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我可以定义结构类型如下:

In Scala, I can define structural types as follows:

键入可按下= {DEF按():单位}

这意味着我可以定义这需要作为一个参数的东西,可压,这样的函数或方法:

This means that I can define a function or method which takes as an argument something that is Pressable, like this:

高清美孚(I:可按下){//等

我传递给这个函数的对象必须为它定义一个方法调用按(),在所定义的类型签名匹配。类型 - 不带任何参数,返回单位(Scala的版本无效的)

The object which I pass to this function must have defined for it a method called press() that matches the type signature defined in the type - takes no arguments, returns Unit (Scala's version of void).

我甚至可以用结构型式直列:

I can even use the structural type inline:

高清foo的。(我:{DEF按():单位}){//等等

它基本上允许程序员有鸭打字的所有优点,同时还具有编译时类型检查的好处。

It basically allows the programmer to have all the benefits of duck typing while still having the benefit of compile-time type checking.

C#有类似的东西?我GOOGLE了,但找不到任何东西,但我不熟悉C#中的任何深度。如果没有,是否有计划添加此?

Does C# have something similar? I've Googled but can't find anything, but I'm not familiar with C# in any depth. If there aren't, are there any plans to add this?

推荐答案

没有,也没有计划,我知道的。只有命名(而非结构)亚型(如接口)。

No, and no plans that I know of. Only named (rather than structural) subtyping (e.g. interfaces).

(其他人可能还想看看

http://en.wikipedia.org/wiki/Nominative_type_system

http://en.wikipedia.org/wiki/Structural_type_system

(有些人可能会指出一些异国情调的角落情况下,如使用的foreach 语句为的GetEnumerator 结构打字,但这是的例外,而不是规则。)

(A few people may point out some exotic corner cases, like the foreach statement using structural typing for GetEnumerator, but this is the exception rather than the rule.)

这篇关于C#有一个相当于Scala的结构性打字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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