我有以下课程:
abstract class AClass { } class Foo : AClass { } class Bar : AClass { }
当我试图使用它们时:
AClass myInstance; myInstance = true ? new Foo() : new Bar();
由于“CSharpTest.Class1.Foo”和“CSharpTest.Class1.Bar”之间没有隐式转换,因此无法确定条件表达式的类型,因此无法编译此代码.
但下面的示例编译ok:
if (true) { myInstance = new Foo(); } else { myInstance = new Bar(); }
这也没关系
myInstance = true ? (AClass) new Foo() : new Bar();
要么
myInstance = true ? new Foo() : (AClass) new Bar();
为什么条件运算符和if子句的行为有如此大的差异?
解决方法
由于X和Y之间不存在隐式转换(即使它们共享共同的基础,它们之间也不存在隐式转换),因此您需要将其中一个显式转换为基类,以便存在隐式转换.
来自C#规范的详细说明:
The second and third operands of the
?:
operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,If X and Y are the same type,then this is the type of the conditional expression.
Otherwise,if an implicit conversion (Section 6.1) exists from X to Y,but not from Y to X,
then Y is the type of the conditional expression.Otherwise,if an implicit conversion (Section 6.1) exists from Y to X,but not from X to Y,
then X is the type of the conditional expression.Otherwise,no expression type can be determined,and a compile-time error occurs.