条件运算符很困惑,但为什么? [英] The conditional operator gets confused, but why?
问题描述
假设有两个类,同一超类的两个后代,如下:
Assume two classes, both descendants of the same superclass, like this:
class MySuperClass{}
class A : MySuperClass{}
class B : MySuperClass{}
传递编译器:
MySuperClass p = myCondition ? new A() : new B();
编译器提示A和B不兼容(无法确定条件表达式的类型因为在'A'和'B'之间没有隐式转换 [CS0173])。但他们都是类型MySuperClass,所以在我看来这应该工作。这不是一件大事;一个简单的转换就是启发编译器所需要的。但是这肯定是C#编译器的障碍?你不同意吗?
The compiler complains that A and B are not compatible (Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'B' [CS0173] ). But they are both of type MySuperClass, so in my opinion this should work. Not that it's a big deal; a simple cast is all it takes to enlighten the compiler. But surely it's a snag in the C# compiler? Don't you agree?
推荐答案
条件的结果应该是相同的类型。他们不是。
The results of the conditional should be of the same type. They are not.
从 MSDN ,(?:Operator):
From MSDN, (?: Operator):
first_expression和second_expression的类型必须相同,
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.
由于 A
code> B 不是相同的类型,你似乎没有定义一个隐式转换,编译器抱怨。
Since A
and B
are not the same type and you don't seem to have defined an implicit conversion, the compiler complains.
这篇关于条件运算符很困惑,但为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!