<分区>
我刚遇到这个(编写代码来演示“问题”):
public ICollection<string> CreateCollection(int x)
{
ICollection<string> collection = x == 0
? new List<string>()
: new LinkedList<string>();
return collection;
}
编译器提示:
Fehler CS0173: Der Typ des bedingten Ausdrucks kann nicht bestimmt werden, weil keine implizite Konvertierung zwischen "System.Collections.Generic.List" und "System.Collections.Generic.LinkedList" erfolgt.
大致翻译为:
The type of the conditional operator can not be determined, because there is no implicit conversion between List and LinkedList.
我明白为什么编译器会提示,但是嘿,来吧。它试图装傻。我可以看到这两个表达式不是同一类型,但有一个共同的祖先,作为奖励,左侧的类型也是一个共同的祖先。我相信编译器也能看到它。如果左侧被声明为 var
,我可以理解这个错误。
我在这里错过了什么?
编辑:
我接受 James Gaunt 的解释。也许只是为了说清楚。我可以很好地阅读编译器规范。我想明白为什么。为什么有人决定以这种方式编写规范。这种设计背后一定有原因。根据詹姆斯的设计原则是“没有惊喜”。 CodeInChaos 还解释了如果编译器尝试从共同祖先推断出类型,您可能会遇到什么意外。