C# 和 VB 中类型参数变化的语法选择

发布于 2024-08-28 23:21:10 字数 592 浏览 7 评论 0原文

在 C# 和 VB 中,类型参数修饰符用于表达类型参数的方差。例如,C# 版本如下所示:

interface Foo<in X, out Y> { }

VB 版本如下所示:

Interface Foo(Of In X, Out Y)

End Interface

由于方差规范基本上限制了类型参数的使用位置和方式,因此我倾向于将它们视为对类型参数的附加约束。

我只是好奇为什么他们没有这样的代表。我的意思是,为什么它们在两种语言中都表示为类型参数的附加修饰符,而不是添加到类型约束列表中?如果它们是类型约束,则 C# 版本将如下所示:

interface Foo<X, Y> where X:in where Y:out { }

VB 版本将如下所示:

Interface Foo(Of X As In, Y As Out)

End Interface

那么,有谁知道在这些语言中表达类型参数差异的特定语法选择背后是否存在某种推理,或者这只是随机的吗?

In both C# and VB, type parameter modifiers are used to express the variance of type parameters. For example, the C# version looks like:

interface Foo<in X, out Y> { }

and the VB version looks like:

Interface Foo(Of In X, Out Y)

End Interface

Since variance specifications basically restrict where and how a type parameter can be used, I tend to think of them as additional constraints on type parameters.

I'm just curious as to why they aren't represented so. I mean, why are they represented in both languages as additional modifiers on type parameters, instead of being added to the type constraint list? If they were type constraints, the C# version would've looked like:

interface Foo<X, Y> where X:in where Y:out { }

and the VB version would've looked like:

Interface Foo(Of X As In, Y As Out)

End Interface

So, does anyone know if there was some reasoning behind the particular syntax choice for expressing type parameter variance in these languages, or was it just random?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柒七 2024-09-04 23:21:10

我认为语言设计者在这里做出了很好的选择。

原因是协变和逆变不是对类型(在您的情况下为 X/Y)的约束,而是对接口本身的约束。

如果您使用 where X: inOf X As In 语法,则建议对类型 X 进行约束。然而,协变和逆变实际上是接口本身的“约束”——接口的泛型类型将如何使用类型“T”。例如,通过说:

interface Foo<out X> {}

您说“此接口仅使用X作为输出”,这实际上是在说您限制使用X 以允许协方差的方式。

这与“X 需要限制为特定类型”有很大不同,因为这不是对 X 的限制。

通过引入新语法,语言设计者允许我们通过不混合消息来更有效地概念化这一点。

I think the language designers made a good choice here.

The reason for this is that covariance and contravariance are not constraints on the type (X/Y in your case), but rather on the interface itself.

If you used the where X: in or Of X As In syntax, you're suggesting a constraint on the type X. However, covariance and contravariance are really "constraints" on the interface itself - how the generic type of interface is going to use the type "T". For example, by saying:

interface Foo<out X> {}

You're saying "This interface only uses X as an output", which really is saying that you're constraining your usage of X in a way that allows covariance.

This is very different than saying "X needs to be constrainted to a specific type", since this isn't a constraint on X.

By introducing a new syntax, the language designers have allowed us to conceptualize this more effectively by not mixing messages.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文