前置与前置C#中的发布增量 [英] Pre- & Post Increment in C#
问题描述
我对C#编译器如何处理前后增量和递减感到困惑.
I am a little confused about how the C# compiler handles pre- and post increments and decrements.
当我编写以下代码时:
int x = 4;
x = x++ + ++x;
x
之后将具有值10.我认为这是因为预递增将x
设置为5
,这使得它将5+5
评估为10
.然后,后增量会将x
更新为6
,但是不会使用此值,因为随后会将10
分配给x
.
x
will have the value 10 afterwards. I think this is because the pre-increment sets x
to 5
, which makes it 5+5
which evaluates to 10
. Then the post-increment will update x
to 6
, but this value will not be used because then 10
will be assigned to x
.
但是当我编码时:
int x = 4;
x = x-- - --x;
然后x
将是2
.谁能解释为什么会这样?
then x
will be 2
afterwards. Can anyone explain why this is the case?
推荐答案
x--
将为4,但在--x
时刻将为3,因此最终将为2,那么您将拥有>
x--
will be 4, but will be 3 at the moment of --x
, so it will end being 2, then you'll have
x = 4 - 2
顺便说一句,您的第一种情况是x = 4 + 6
btw, your first case will be x = 4 + 6
这是一个小示例,它将打印出每个零件的值,也许这样您会更好地理解它:
Here is a small example that will print out the values for each part, maybe this way you'll understand it better:
static void Main(string[] args)
{
int x = 4;
Console.WriteLine("x++: {0}", x++); //after this statement x = 5
Console.WriteLine("++x: {0}", ++x);
int y = 4;
Console.WriteLine("y--: {0}", y--); //after this statement y = 3
Console.WriteLine("--y: {0}", --y);
Console.ReadKey();
}
这将打印出来
x++: 4
++x: 6
y--: 4
--y: 2
这篇关于前置与前置C#中的发布增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!