C#字节加法运算 [英] C# byte addition operation
问题描述
可能有人点我,为什么在这里:
Could someone point me, why here:
Byte b = 100;
b = (Byte)(b+200);
我必须使用显式类型转换。但在这里
I have to use explicit type conversion. But here
Byte b = 100;
b += 200;
我不需要做到这一点?
I don't need to do this?
难道编译器生成不同的IL $ C $下这两个案?而这种情况下,是更好吗?
Does compiler generate different IL code for this two cases? And which case is better?
推荐答案
由于在标准允许的话(见第二下面的情况下):
Because the standard permits it (see the second case below):
的形式的操作X
的运算的 =
是
通过应用二元运算符重载解析处理(§14.2.4),好像操作是写 X
的运算的是
。然后,
14.14.2 Compound assignment
An operation of the form
x
op=
y
is processed by applying binary operator overload resolution (§14.2.4) as if the operation was writtenx
opy
. Then,
-
如果选定的运算符的返回类型可隐式转换到
X型
,该运算按X = X
的运算的是
,但X
只计算一次
If the return type of the selected operator is implicitly convertible to the type of
x
, the operation is evaluated asx = x
opy
, except thatx
is evaluated only once.
否则,如果选定的运营商为p $ pdefined运营商,如果所选运算符的返回类型是显式转换到 X
A型$,如果是
隐式转换为对 X型
或运算符是移位运算符,则操作进行评估为 X =(T)(X
的运算的 Y)
,其中 T
是 X
,但 X
只计算一次。
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.
在IL code应该是在这种情况下基本相同。当然,如果评估 B
有副作用,它会在两次评估B =(字节)B + 200
情况下,只有一次使用复合赋值的时候。
The IL code should be essentially identical in this case. Of course, if evaluating b
has side effects, it will be evaluated twice in the b = (byte)b + 200
case and only once when using compound assignment.
这篇关于C#字节加法运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!