作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这可以在 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 delegates 。 ValueType
两者都不是。
事实上,当我尝试用自己的代码复制此功能时,我失败了:
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.
关于c# - 是什么让 ValueTuple 具有协变性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411397/
我是一名优秀的程序员,十分优秀!