C# 4.0 元组是协变的吗 [英] Is C# 4.0 Tuple covariant

查看:17
本文介绍了C# 4.0 元组是协变的吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我会自己检查一下,但我还没有 VS2010)

(I would check this out for myself, but I don't have VS2010 (yet))

假设我有 2 个基本接口:

Say I have 2 base interfaces:

IBaseModelInterface
IBaseViewInterface

以及实现这些的 2 个接口:

And 2 interfaces realizing those:

ISubModelInterface : IBaseModelInterface
ISubViewInterface : IBaseViewInterface

如果我定义一个 Tuple 我想根据返回 Tuple 的工厂的结果来设置它.

If I define a Tuple<IBaseModelInterface, IBaseViewInterface> I would like to set that based on the result of a factory that returns Tuple<ISubModelInterface, ISubViewInterface>.

在 C# 3 中,即使子接口实现了基本接口,我也无法做到这一点.而且我很确定如果我使用的是 IEnumerable<IBaseModelInterface>,C# 4 允许我这样做,因为它现在使用 in 关键字定义以允许协方差.那么 Tuple 是否允许我这样做?

In C# 3 I can't do this even though the sub interfaces realize the base interfaces. And I'm pretty sure C# 4 lets me do this if I was using IEnumerable<IBaseModelInterface> because it's now defined with the in keyword to allow covariance. So does Tuple allow me to do this?

据我了解,协方差只允许在接口上使用,这是否意味着需要有一个 ITuple<T1, T2> 接口?这存在吗?

From what (little) I understand, covariance is only allowed on interfaces, so does that mean there needs to be an ITuple<T1, T2> interface? Does this exist?

推荐答案

Tuple 是一个类(嗯,一个类族)——它在定义上是不变的.正如您稍后提到的,只有接口和委托类型支持 .NET 4 中的泛型变化.

Tuple is a class (well, a family of classes) - it's invariant by definition. As you mention later on, only interfaces and delegate types support generic variance in .NET 4.

据我所知,没有 ITuple 接口.可能有一个是协变的,因为元组是不可变的,因此您只能从 API 中取出"值.

There's no ITuple interface that I'm aware of. There could be one which would be covariant, as the tuples are immutable so you only get values "out" of the API.

这篇关于C# 4.0 元组是协变的吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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