gpt4 book ai didi

c# - 三元运算符和协变强制

转载 作者:行者123 更新时间:2023-11-30 13:56:33 25 4
gpt4 key购买 nike

我声明变量,

IList<int> list;

然后我写声明,

if(true)
{
list = new List<int>();
}
else
{
list = new int[0];
}

我有一些琐碎且毫无意义的代码,可以在没有警告的情况下进行编译。如果我写声明,

list = true ? new List<int>() : new int[0];

我收到编译器警告,

There is no implicit conversion between 'System.Collections.Generic.List<int>' and 'int[]'

为什么三元运算符有这个限制?两者 List<int>int[]实现 IList<int> .


发布答案

来自 C# 5.0 规范的 7.14 条件运算符部分

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

  1. 如果 x 的类型为 X,而 y 的类型为 Y,则

    • 如果存在从 X 到 Y 的隐式转换 (§6.1),但不存在从 Y 到 X 的隐式转换,则 Y 是条件表达式的类型。

    • 如果存在从 Y 到 X 的隐式转换 (§6.1),但不存在从 X 到 Y,则 X 是条件表达式的类型。

    • 否则无法确定表达式类型,会出现编译时错误。

  2. 如果只有 x 和 y 中的一个具有类型,并且 x 和 y 都可以隐式转换为该类型,则该类型就是条件表达式的类型。

  3. 否则无法确定表达式类型,会出现编译时错误。

最佳答案

分配给 list 不是问题.表达式 true ? new List<int>() : new int[0] 有问题.这种表达在任何情况下都是不合法的。

如果您引用 documentation ,您会找到此信息。

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

在这种情况下情况并非如此。

关于c# - 三元运算符和协变强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26934911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com