Why doesn't implicit conversion from integer to byte work with the conditional operator?

痴心易碎 提交于 2019-12-11 05:53:22

问题


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 type sbyte, byte, short, ushort, uint, or ulong, 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 type ulong, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!