问题
The MSDN page for byte says that you can declare a byte like this:
byte myByte = 255;
and that
In the preceding declaration, the integer literal 255 is implicitly converted from int to byte. If the integer literal exceeds the range of byte, a compilation error will occur.
So I'm struggling to understand why the following gives me a compile error of 'cannot implicitly convert type 'int' to 'byte')
byte value = on ? 1 : 0; // on is defined as a bool earlier
I'm compiling this on VS 2012 as a Windows Store App project, if that makes any difference.
回答1:
Because this:
on ? 1 : 0
Isn't an integer literal. It an expression that returns an integer. Moreover, this expression cannot be evaluated until runtime.
When there's a literal, the compiler can evaluate it at compile time and ensure it satisfies any range requirements - as the page says, it's up to the compiler to produce an error if the value is out of range.
And from your same page:
You cannot implicitly convert non-literal numeric types of larger storage size to byte.
Per @Jeppe Stig Nielsen's comment - it does also work if the value is a constant (it doesn't have to be a literal as the first page says). C# spec says:
6.1.9 Implicit constant expression conversions
An implicit constant expression conversion permits the following conversions:
A constant-expression (§7.19) of type
int
can be converted to typesbyte
,byte
,short
,ushort
,uint
, orulong
, provided the value of the constant-expression is within the range of the destination type.A constant-expression of type
long
can be converted to typeulong
, provided the value of the constant-expression is not negative.
来源:https://stackoverflow.com/questions/12371601/why-doesnt-implicit-conversion-from-integer-to-byte-work-with-the-conditional-o