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.
这篇关于条件运算符感到困惑,但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:条件运算符感到困惑,但为什么呢?
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
