有条件的经营者不能隐式转换? [英] Conditional operator cannot cast implicitly?

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

问题描述

我有点被这个小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;

错误说:不能隐式转换类型'诠释'到'字节'。

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兼容。但是,我们不使用的事实,我们知道x的类型是什么,当我们正在制订y的类型。

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

我们的需求的才能够制定出一个前pression的的类型,而的知道它是什么被分配到。键入信息流的了一个前pression,不是的进入的一名前pression。

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.

要制定出的条件前pression的类型,我们制定出的后果和替代前pressions的类型,挑选更普遍的两种类型,并且成为的类型有条件的前pression。所以在实施例中,条件前pression的类型是int,并且它不是一个常数(除非条件前pression是恒定真或恒定假)。由于它不是一个常数,你不能把它分配给字节;单从类型,而不是从值,当结果不是一个常数。编译器的原因

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前pressions,其中类型信息的确实的从上下文到拉姆达流。获得了正确的逻辑是非常困难的。

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天全站免登陆