使用条件运算符时的隐式转换 [英] No implicit conversion when using conditional operator

查看:192
本文介绍了使用条件运算符时的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

abstract class AClass { }
class Foo : AClass { }
class Bar : AClass { }

而当我试图使用它们:

AClass myInstance;
myInstance = true ? new Foo() : new Bar();



由于条件表达式类型此代码不会编译无法确定,因为没有

This code won't compiling because of the "Type of conditional expression cannot be determined because there is no implicit conversion between 'CSharpTest.Class1.Foo' and 'CSharpTest.Class1.Bar'"

但下面编译好的样品间的隐式转换$ b

But following samples compiling ok:

if (true)
{
    myInstance = new Foo();
}
else
{
    myInstance = new Bar();
}

这是也没关系:

myInstance = true ? (AClass) new Foo() : new Bar();

myInstance = true ? new Foo() : (AClass) new Bar();



为什么没有在有条件的经营者的行为,如果条款?

Why there is so big difference in behavior of the conditional operator and if clause?

推荐答案

这是预期的行为。

由于没有的隐式转换的X和Y之间存在(即使他们都有一个共同的基础,它们之间的隐式转换),你需要的显式转换的人(至少)一个基类,这样的隐式转换存在。

Since no implicit conversion exists between X and Y (even if they share a common base, there is no implicit conversion between them), you need to explicitly cast (at least) one of them to the base class so that an implicit conversion exists.

从C#规范的详细说明:

A detailed explanation from the C# specification:

第二个和第三个操作数在的:操作员控制条件表达式的类型。设X和Y是类型的第二和第三运算数的。然后,

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,

如果X和Y是相同的类型,则这是在条件表达式的类型。

If X and Y are the same type, then this is the type of the conditional expression.

否则,如果隐式转换(第6.1节)存在从X到Y,而不是从Y到X,
则Y为条件表达式的类型。

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.

否则,如果隐式转换(第6.1节)从Y到X的存在,但不从X到Y,
则X是条件表达式的类型。

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.

否则,没有表达式的类型可确定,并发生编译时错误。

这篇关于使用条件运算符时的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆