表达式内的操作数是否根据以下规则提升为更大的类型?
如果数值表达式包含不同数值类型的操作数(常量和变量),则操作数是否根据以下规则提升为更大的类型:
- 如果操作数的类型为
byte
、sbyte
、char
、short
、ushort
,它们会转换为int
类型 - 如果其中一个操作数是
int
,则所有操作数都转换为int
- 如果表达式还包含
uint
和int
类型的操作数,则所有操作数都转换为long
- 如果其中一个操作数为
long
,则 - 当表达式包含
ulong
类型的操作数时, 所有操作数都将转换为long
和long
,则操作数将转换为float
- 如果其中一个操作数为
float
,则所有操作数都将转换为float
code> - 如果其中一个操作数为
double
,则所有操作数都会转换为double
假设数值表达式包含不同类型的操作数,所有操作数首先会转换为单一数值类型,然后运行时才会尝试计算结果?例如,如果变量 b1
和 b2
为 byte
类型,而 i1
为 int< /code> 类型,在计算
(b1+b2)
之前将 b1
和 b2 get
转换为 int:
int i2=(b1+b2)+i1
If numeric expression contains operands (constants and variables) of different numeric types, are operands promoted to larger types according to the following rules:
- if operands are of types
byte
,sbyte
,char
,short
,ushort
, they get converted toint
type - If one of the operands is
int
, then all operands are converted toint
- if expression also contains operands of types
uint
andint
, then all operands are converted tolong
- If one of operands is
long
, then all operands are converted tolong
- if expression contains operands of type
ulong
andlong
, then operands are converted tofloat
- If one of the operands is
float
, then all operands are converted tofloat
- if one of operands is
double
, then all operands are converted todouble
Assuming numeric expressions contains operands of different types, will all operands first get converted to a single numeric type, and only then will the runtime try to compute the result? For example, if variables b1
and b2
are of byte
type, while i1
is of int
type, will b1
and b2 get
converted to int prior to computing (b1+b2)
:
int i2=(b1+b2)+i1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
括号的优先级高于
+
,因此转换通常会在添加b1
和b2
之后进行。但是,+
运算符对于byte
没有重载,因此必须首先将byte
提升为int
。进一步阅读:
The parentheses are of higher precedence than
+
, so the conversion would normally take place afterb1
andb2
have been added. However, the+
operator does not have an overload forbyte
s, so thebyte
s must first be promoted toint
s.Further reading:
你的规则有一些真理元素,但在技术上并不精确。
以下是 C# 语言规范的相关摘录
根据上述规范,是的,
字节 b1, b2
会被二进制数字提升为int
为二元运算符+
。Your rules have some elements of truths, but is technically imprecise.
Here are the relevant excerpts from the C# Language Specification
As per the specification above, yes,
byte b1, b2
are subject to binary numeric promotion toint
for the binary operator+
.