在C#是什么敏++和++敏之间的区别?
我有一个很难理解有什么区别在C#这种方式递增的变量之间:
I'm having a hard time understanding what the difference is between incrementing a variable in C# this way:
myInt++;
和
++myInt;
在将永远无论你使用哪一个?
When would ever matter which one you use?
我给voteCount ++为最佳答案。或者我应该给它++ voteCount ...
I'll give voteCount++ for the best answer. Or should I give it ++voteCount...
有是对自己写的时候(如图所示)没有区别 - 在这两种情况下会敏1递增
There is no difference when written on its own (as shown) - in both cases myInt will be incremented by 1.
不过是有区别的,当你在一个前pression,例如使用是这样的:
But there is a difference when you use it in an expression, e.g. something like this:
MyFunction(++myInt);
MyFunction(myInt++);
在第一种情况下,敏递增和新的/递增的值被传递给MyFunction的()。在第二种情况下,敏的旧值传递给MyFunction的()(但敏还在递增,因此调用该函数之前)。
In the first case, myInt is incremented and the new/incremented value is passed to MyFunction(). In the second case, the old value of myInt is passed to MyFunction() (but myInt is still incremented before the function is called).
另一个例子是这样的:
int myInt = 1;
int a = ++myInt;
// myInt is incremented by one and then assigned to a.
// Both myInt and a are now 2.
int b = myInt++;
// myInt is assigned to b and then incremented by one.
// b is now 2, myInt is now 3
BTW:作为唐在评论中指出,同样的规则也适用于递减操作,而这些操作正确的术语是:
BTW: as Don pointed out in a comment the same rules are also valid for decrement operations, and the correct terminology for these operations are:
++i; // pre-increment
i++; // post-increment
--i; // pre-decrement
i--; // post-decrement
由于乔恩斯基特所指出的:
其他人所示,其中它使
差,并评论说,作为
单个语句不作
区别。
Others have shown where it makes a difference, and have commented that as a single statement it doesn't make a difference.
我想补充一点,它几乎
总是一个坏主意,它用它
有差别。我怀疑有
也许有些时候它更
可读有code,如:
I'd like to add that it's almost always a bad idea to use it where it makes a difference. I suspect there may be some times where it's more readable to have code such as:
Console.WriteLine("Foo: {0}", foo++);
比
than:
Console.WriteLine("Foo: {0}", foo);
foo++;
......但他们是非常罕见的!该
这两个样品的后者使
立即订购晶莹剔透 -
前者需要一点思考
(我脑子不好,反正)。想到
可读性第一。
... but they're very rare! The latter of these two samples makes the ordering crystal clear immediately - the former requires a bit of thinking (to my poor brain, anyway). Think of the readability first.