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

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)