条件运算符感到困惑,但为什么呢?

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{}

那么这个赋值不会通过编译器:

Then this assignment won't pass the compiler:

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,(?:运算符):

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.

由于 AB 不是同一类型,并且您似乎没有定义隐式转换,因此编译器会抱怨.

Since A and B are not the same type and you don't seem to have defined an implicit conversion, the compiler complains.

这篇关于条件运算符感到困惑,但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:条件运算符感到困惑,但为什么呢?

基础教程推荐