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.
由于 A 和 B 不是同一类型,并且您似乎没有定义隐式转换,因此编译器会抱怨.
Since A and B are not the same type and you don't seem to have defined an implicit conversion, the compiler complains.
这篇关于条件运算符感到困惑,但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:条件运算符感到困惑,但为什么呢?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
