gpt4 book ai didi

c# - 为什么 x = x + 100 与编译为相同 IL 的 x += 100 的处理方式不同?

转载 作者:太空狗 更新时间:2023-10-29 20:26:29 28 4
gpt4 key购买 nike

我们知道这两个加法语句是等价的,编译成相同的IL代码:

int x = 100;

x += 100;
x = x + 100;

但是,当需要显式强制转换时,我注意到了一些奇怪的事情:

byte b = 100;

b += 200; // Compiles (1)
b = b + 200; // Cannot implicitly convert int to byte (2)
b = (byte) (b + 200); // Compiles (3)

很明显为什么第二条语句需要显式转换,因为加法的结果是一个整数。但对我来说奇怪的是第一句话。它编译为与第三条语句完全相同的 IL,因此看起来编译器为我们添加了一个应该是显式的强制转换。但是在第二个语句中做不到。

这对我来说似乎是矛盾的,因为我希望第一个语句等同于第二个并且永远不会编译,那么为什么它会编译呢?

注意:当需要从 longint 的显式转换时,这不会编译:

int x = 100;
long y = 200;

x += y;

最佳答案

你真的需要去 specs对于这类信息(并且很难理解措辞)。然而,直接从马嘴里说出来

12.18.3 Compound assignment

An operation of the form x op= y is processed by applying binary operator overload resolution (§12.4.5) as if the operation was written x op y. Then,

  • If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x
    op y
    , except that x is evaluated only once.

  • Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x , and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.

  • Otherwise, the compound assignment is invalid, and a binding-time error occurs.

...

blah blah blah

...

The second rule above permits x op= y to be evaluated as x = (T)(x op y) in certain contexts. The rule exists such that the predefined operators can be used as compound operators when the left operand is of type sbyte, byte, short, ushort, or char. Even when both arguments are of one of those types, the predefined operators produce a result of type int, as described in §12.4.7.3. Thus, without a cast it would not be possible to assign the result to the left operand.

The intuitive effect of the rule for predefined operators is simply that x op= y is permitted if both of x op y and x = y are permitted.

byte b = 0;
char ch = '\0';
int i = 0;
b += 1; // Ok
b += 1000; // Error, b = 1000 not permitted
b += i; // Error, b = i not permitted
b += (byte)i; // Ok
ch += 1; // Error, ch = 1 not permitted
ch += (char)1; // Ok

the intuitive reason for each error is that a corresponding simple assignment would also have been an error.

简而言之,计算机说不。

关于c# - 为什么 x = x + 100 与编译为相同 IL 的 x += 100 的处理方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240649/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com