关于c#:当看起来没有涉及“long”类型时,不能隐式地将类型’long’转换为’int’


Cannot implicitly convert type 'long' to 'int', when it seems no `long` type involved

另一个跟踪错误的帖子Cannot implicitly convert type 'long' to 'int'

1
2
3
4
5
6
7
8
public int FindComplement(int num) {
    uint i = 0;
    uint mask = ~i;

    while((mask&num) != 0) mask <<= 1;
    //return ~mask^num; //<-- error CS0266
    return (int)~mask^num; //<--it works with (int)
}

不好意思问了太多问题,我想知道为什么return ~mask^num会引起错误,比如

error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)

在我的环境中,return ~mask^num;会导致错误,而return (int)~mask^num可以工作。这里似乎没有涉及到long型。


您试图对操作数intuint执行^操作。没有这样的运算符,因此两个操作数都转换为long,并使用long ^(long, long)运算符。

根据ECMA C_5规范第12.4.7.1节:

Numeric promotion consists of automatically performing certain implicit conversions of the operands of
the predefined unary and binary numeric operators. Numeric promotion is not a distinct mechanism, but
rather an effect of applying overload resolution to the predefined operators. Numeric promotion
specifically does not affect evaluation of user-defined operators, although user-defined operators can be
implemented to exhibit similar effects.

从12.4.7.3:

Binary numeric promotion occurs for the operands of the predefined +, –, *, /, %, &, |, ^, ==, !=, >, <, >=,
and <= binary operators. Binary numeric promotion implicitly converts both operands to a common type which, in case of the non-relational operators, also becomes the result type of the operation. Binary numeric promotion consists of applying the following rules, in the order they appear here:

  • ... (rules that don't apply here)
  • 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.


uint类型保存0到4294967295之间的数字。这意味着当您使用一个正则int作为参数num时,您正在对两个具有两个不同范围的不同类型执行操作。因此,为了不得到这个错误,您可以对所有内容使用ints。