6

如果数值表达式包含不同数值类型的操作数(常量和变量),则根据以下规则将操作数提升为更大的类型:

  1. 如果操作数的类型为byte, sbyte, char, short, ushort,它们将被转换为int类型
  2. 如果其中一个操作数是int,则所有操作数都转换为int
  3. 如果表达式还包含类型为uintand的操作数int,则所有操作数都转换为long
  4. 如果操作数之一是long,则所有操作数都转换为long
  5. 如果表达式包含 and 类型的操作数ulonglong则操作数转换为float
  6. 如果其中一个操作数是float,则所有操作数都转换为float
  7. 如果操作数之一是double,则所有操作数都转换为double

假设数字表达式包含不同类型的操作数,所有操作数是否会首先转换为单个数字类型,然后运行时才会尝试计算结果?例如,如果变量b1andb2byte类型,whilei1int类型,将b1和 b2get在计算之前转换为 int (b1+b2)

int i2=(b1+b2)+i1
4

2 回答 2

1
于 2010-06-20T19:25:21.427 回答
1

The parentheses are of higher precedence than +, so the conversion would normally take place after b1 and b2 have been added. However, the + operator does not have an overload for bytes, so the bytes must first be promoted to ints.

Further reading:

于 2010-06-20T19:25:29.960 回答