C#奇怪的行为 [英] C# strange behaviour

查看:96
本文介绍了C#奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此代码

consider this code

<br />
<pre lang="midl"><br />
   int j = 1;<br />
   j = j++;</pre><br />


令人惊讶的是,它能产生1、2行没有影响.
MSIL像


amazingly enough it produses 1, 2nd line has no affect.
MSIL looks like

---------------------Loc 0  Stack
IL_0000:  nop
IL_0001:  ldc.i4.1            1           Push 1 onto the stack as int32
IL_0002:  stloc.0     1       -           Pop a value from stack into local variable 0
IL_0003:  ldloc.0     1       1           Load local variable 0 onto stack
IL_0004:  dup         1       1,1         Duplicate the value on the top of the stack
IL_0005:  ldc.i4.1    1       1,1,1       Push 1 onto the stack as int32
IL_0006:  add         1       2,1         Add two values, returning a new value
IL_0007:  stloc.0     2       1           Pop a value from stack into local variable 0
IL_0008:  stloc.0     1       -           Pop a value from stack into local variable 0


最后一行很明显是罪魁祸首.它在Java,JavaScript中的工作原理相同.


quite obvious last line is the culprit. It works the same in Java, JavaScript. C/C++ works fine!

推荐答案

我不会说这是一个错误,与C ++相比,C#具有不同的评估规则.

如果您想要自己的期望,可以按照以下步骤操作:

I would not say it''s a bug, C# has different evaluation rules compared to C++.

If you want what you expect, you can do it as:

j = ++j;



顺便说一句,该行代码的行为在C/C ++中未定义,这取决于各个编译器的实现方式来决定如何处理.有关更多信息,请谷歌查询"C ++序列点".

顺便说一句,C#行为也未定义. C#的未来版本可能决定以不同的方式实现此目标(因为它不在标准中).通常,最好避免编写在赋值运算符的任一侧多次修改相同变量的代码.



And by the way, the behavior for that line of code is undefined in C/C++ and it''s up to the individual compiler implementations to decide how to handle this. For more information, google for "C++ sequence points".

BTW the C# behavior is undefined too. A future version of C# may decide to implement this differently (since it''s not in the standard). In general it''s best to avoid writing code where the same variable is modified multiple times on either side of an assignment operator.


> C/C ++可以正常工作!

它并不总是有效-未指定行为,因为j = j++缺少序列点 [
> C/C++ works fine!

It does not always work - the behavior is not specified, because j = j++ lacks a sequence point[^] between the two assignments.


这篇关于C#奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆