在 C# 中,我可以将一个数字(最多 255)直接分配给字节类型的变量:
byte red = 255;
但是,如果我使用条件运算符在更复杂的语句中执行此操作:
byte red = (redNode != null) ? byte.Parse(redNode.Value) : 255;
我收到错误消息:“CS0266 无法将类型‘int’隐式转换为‘byte’。存在显式转换(是否缺少强制转换?)”。
我需要为 255 显式转换为字节:
byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255;
为什么需要这个类型转换?
C# 中的数字文字是int
,而不是byte
。尝试 0xff
。
有no implicit conversion from int to byte , 而第一个语句 byte red = 255;
是一个特例。
A constant expression of type int can be converted to sbyte, byte,
short, ushort, uint, or ulong, provided the value of the constant
expression is within the range of the destination type.
这并不能解释为什么它不转换第二个表达式中的常量 255,对吗?
不需要在第二个表达式中转换 255,因为 there is an implicit conversion from byte to int .所以byte.Parse(redNode.Value)
被转换为int
。所以 (redNode != null) ? byte.Parse(redNode.Value) : 255;
是 int
类型 - 因为它不是常量表达式,所以不再有到 byte
的隐式转换.
您认为错误消息要求您这样做:
byte red = (redNode != null) ? byte.Parse(redNode.Value) : (byte)255;
但它确实要求你这样做:
byte red = (byte)((redNode != null) ? byte.Parse(redNode.Value) : 255);