关于.net:+ =运算符是否确保在C#中进行EXPLICIT转换或隐式CASTING?

Does += operator ensures an EXPLICIT conversion or implicit CASTING in C#?

下面的示例编译:

1
2
3
4
5
6
public static void Main()
{
    Byte b = 255;
    b += 100;

}

但下面这个失败了

1
2
3
4
5
   public static void Main()
    {
        Byte b = 255;
        b = b + 100;
    }

具有

Error 1 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

这是否意味着对于c+=运算符提供显式转换?


埃里克·利珀特很详细地回答了你的问题。

Another interesting aspect of the predefined compound operators is
that if necessary, a cast – an allegedly"explicit" conversion – is
inserted implicitly on your behalf. If you say

1
2
short s = 123;
s += 10;

then that is not analyzed as s = s + 10 because short plus int is int,
so the assignment is bad. This is actually analyzed as

1
s = (short)(s + 10);

so that if the result overflows a short, it is automatically cut back
down to size for you.

另见第二部分。