c# - 是什么让 ValueTuple 具有协变性?

标签 c# covariance valuetuple

这可以在 C# 7.3(框架 4.8)中正确编译:

(string, string) s = ("a", "b");
(object, string) o = s;

我知道这是以下内容的语法糖,它也可以正确编译:

ValueTuple<string, string> s = new ValueTuple<string, string>("a", "b");
ValueTuple<object, string> o = s;

所以,看起来 ValueTuples 可以被分配 covariantly这太棒了!

不幸的是,我不明白为什么:我的印象是 C# only supported covariance on interfaces and delegatesValueType 两者都不是。

事实上,当我尝试用自己的代码复制此功能时,我失败了:

struct MyValueTuple<A, B>
{
    public A Item1;
    public B Item2;

    public MyValueTuple(A item1, B item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}

...

MyValueTuple<string, string> s = new MyValueTuple<string, string>("a", "b");
MyValueTuple<object, string> o = s;
// ^ Cannot implicitly convert type 'MyValueTuple<string, string>' to 'MyValueTuple<object, string>'

那么,为什么 ValueTuple 可以协变赋值,而 MyValueTuple 却不能?

最佳答案

我相信这里实际发生的是解构赋值。元组分配将尝试隐式转换其组件,并且由于可以将 string 分配给 object,这就是这里发生的情况。

The language supports assignment between tuple types that have the same number of elements, where each right-hand side element can be implicitly converted to its corresponding left-hand side element. Other conversions aren't considered for assignments.

Source

See it on sharplab.io

关于c# - 是什么让 ValueTuple 具有协变性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411397/

相关文章:

c# - 为什么要使用 ReaderWriterLockSlim.EnterReadLock?

c# - 单元测试 ASP.NET(不是 MVC)——如何通过 "Request is not Available in this context."?

c# - 如何在 Form 的关闭事件中停止 BackgroundWorker?

C# 子类返回类型的协方差

c# - ValueTuple 不支持 DisplayMemberPath。组合框,WPF

c# - 我可以在 C# 中使用无类型集合吗

covariance - 有人可以解释类型协方差/逆变和范畴论之间的联系吗?

c# - 复杂泛型中的无效方差

c# 7.2 默认表达式和等于(错误?)