为什么在使用条件运算符时需要额外的转换?
Why do I need an extra cast when using the conditional operator?
在 C# 中,我可以将一个数字(最多 255)直接分配给字节类型的变量:
byte red = 255;
但是,如果我使用条件运算符在更复杂的语句中执行此操作:
byte red = (redNode != null) ? byte.Parse(redNode.Value) : 255;
我得到一个错误:"CS0266 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)"。
我需要为 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);
在 C# 中,我可以将一个数字(最多 255)直接分配给字节类型的变量:
byte red = 255;
但是,如果我使用条件运算符在更复杂的语句中执行此操作:
byte red = (redNode != null) ? byte.Parse(redNode.Value) : 255;
我得到一个错误:"CS0266 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)"。
我需要为 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);