c# - 为什么在使用条件运算符时需要额外的转换?

标签 c# casting conditional-operator

<分区>

在 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);

关于c# - 为什么在使用条件运算符时需要额外的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37525573/

相关文章:

java - 使用 Math.random() 的表达式总是返回相同的值

c++ - "?"和 ":"序列实际调用的是什么?

c++ - 如何在不同类型的值之间进行选择以传递给多态函数?

C# 启动电源选项

c# - 语法 : return _(); IEnumerable<TSource> _() 的含义

c++ - 是否可以将对象转换为不相关的类?

java - 无法从 Object 转换为 char

objective-c - '?:' 和 objective-c 中的 if 语句有什么区别吗?

c# - 使用 SqlDataSource 时向 DropDownList 项目添加除值之外的属性

c# - DbContext 和范围依赖