按位运算,ulong 和 int

Bitwise operations, ulong and int

我刚刚发现 C# 不允许您对 ulongint 执行按位运算。 intuintlongulong 的所有其他组合都有效,但其中一个组合无效。

但是,如果不是int,我有const int,一切都很好。

这是怎么回事?为什么 int & ulong 无效,但 const int & ulong 有效?


损坏:

int mask = 0x1110;
ulong value = 0x1010;

var result = mask & value; // Compilation error: "Operator '&' cannot be applied to operands of type 'int' and 'ulong'"

工作:

const int mask = 0x1110;
ulong value = 0x1010;

var result = mask & value; // Works just fine.

此行为并非特定于位运算。根据 C# Language Specification,它适用于所有需要 numeric promotions.

的二进制操作

第 7.6.3.2 节描述了二进制数字提升。我强调了指定您看到的行为的部分:

Binary numeric promotion consists of applying the following rules, in the order they appear here:

  • If either operand is of type decimal, the other operand is converted to type decimal, or a binding-time error occurs if the other operand is of type float or double.
  • Otherwise, if either operand is of type double, the other operand is converted to type double.
  • Otherwise, if either operand is of type float, the other operand is converted to type float.
  • Otherwise, if either operand is of type ulong, the other operand is converted to type ulong, or a binding-time error occurs if the other operand is of type sbyte, short, int, or long.
  • Otherwise, if either operand is of type long, the other operand is converted to type long.
  • Otherwise, if either operand is of type uint and the other operand is of type sbyte, short, or int, both operands are converted to type long.
  • Otherwise, if either operand is of type uint, the other operand is converted to type uint.
  • Otherwise, both operands are converted to type int.

使用const时不会出现问题的原因是允许编译器将const int表达式转换为其他类型,如7.19节所述:

An implicit constant expression conversion (§6.1.9) permits a constant expression of type int to 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.

由于 mask 的值,即 0x1110,适合 ulong,编译器执行提升而不是触发错误。