加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:10:21 所属栏目:百科 来源:网络整理
导读:这个问题在这里已经有一个答案: Nullable types and the ternary operator: why is `? 10 : null` forbidden? 9个 我有以下课程: abstract class AClass { }class Foo : AClass { }class Bar : AClass { } 当我试图使用它们时: AClass myInstance;myInsta
这个问题在这里已经有一个答案:> Nullable types and the ternary operator: why is `? 10 : null` forbidden? 9个
我有以下课程:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读