条件运算符不能隐式转换? [英] Conditional operator cannot cast implicitly?

查看:35
本文介绍了条件运算符不能隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点被这个 C# 的小怪癖难住了:

I'm a little stumped by this little C# quirk:

给定变量:

Boolean aBoolValue;
Byte aByteValue;

以下编译:

if (aBoolValue) 
    aByteValue = 1; 
else 
    aByteValue = 0;

但这不会:

aByteValue = aBoolValue ? 1 : 0;

错误说:无法将类型‘int’隐式转换为‘byte’."

Error says: "Cannot implicitly convert type 'int' to 'byte'."

当然,这个怪物会编译:

And of course, this monstrosity will compile:

aByteValue = aBoolValue ? (byte)1 : (byte)0;

这是怎么回事?

使用 VS2008,C# 3.5

Using VS2008, C# 3.5

推荐答案

这是一个相当常见的问题.

This is a fairly frequently asked question.

在 C# 中,我们几乎总是从内到外推理.当你看到

In C#, we almost always reason from inside to outside. When you see

x = y;

我们计算x的类型是什么,y的类型是什么,y的类型是否与x的赋值兼容.但是我们在计算 y 的类型时并没有使用我们知道 x 的类型这一事实.

we work out what is the type of x, what is the type of y, and whether the type of y is assignment compatible with x. But we do not use the fact that we know what the type of x is when we are working out the type of y.

那是因为 x 可能不止一个:

That's because there might be more than one x:

void M(int x) { }
void M(string x) { }
...
M(y); // y is assigned to either int x or string x depending on the type of y

我们需要能够在不知道表达式被分配给什么的情况下计算出表达式的类型.类型信息从表达式流出,而不是流入表达式.

We need to be able to work out the type of an expression without knowing what it is being assigned to. Type information flows out of an expression, not into an expression.

为了计算出条件表达式的类型,我们计算出结果和替代表达式的类型,在这两种类型中选择更通用的,这就是条件表达式的类型.所以在你的例子中,条件表达式的类型是int",它不是一个常量(除非条件表达式是常量真或常量假).由于它不是常量,因此不能将其分配给字节;当结果不是常量时,编译器仅根据类型而不是值进行推理.

To work out the type of the conditional expression, we work out the type of the consequence and the alternative expressions, pick the more general of the two types, and that becomes the type of the conditional expression. So in your example, the type of the conditional expression is "int", and it is not a constant (unless the condition expression is constant true or constant false). Since it is not a constant, you can't assign it to byte; the compiler reasons solely from the types, not from the values, when the result is not a constant.

所有这些规则的例外是 lambda 表达式,其中类型信息确实从上下文流入 lambda.使这种逻辑正确是非常困难的.

The exception to all these rules is lambda expressions, where type information does flow from the context into the lambda. Getting that logic right was very difficult.

这篇关于条件运算符不能隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆