小编Ale*_*der的帖子

使用条件运算符时没有隐式转换

我有以下课程:

abstract class AClass { }
class Foo : AClass { }
class Bar : AClass { }
Run Code Online (Sandbox Code Playgroud)

当我试图使用它们时:

AClass myInstance;
myInstance = true ? new Foo() : new Bar();
Run Code Online (Sandbox Code Playgroud)

此代码将无法编译,因为"无法确定条件表达式的类型,因为'CSharpTest.Class1.Foo'和'CSharpTest.Class1.Bar'之间没有隐式转换"

但是以下样本编译好了:

if (true)
{
    myInstance = new Foo();
}
else
{
    myInstance = new Bar();
}
Run Code Online (Sandbox Code Playgroud)

这也没问题:

myInstance = true ? (AClass) new Foo() : new Bar();
Run Code Online (Sandbox Code Playgroud)

要么

myInstance = true ? new Foo() : (AClass) new Bar();
Run Code Online (Sandbox Code Playgroud)

为什么条件运算符和if子句的行为有如此大的差异?

c# oop

15
推荐指数
2
解决办法
4232
查看次数

标签 统计

c# ×1

oop ×1