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

4

本文介绍了条件运算符感到困惑,但为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设有两个类,都是同一个超类的后代,如下所示:

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.

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14