什么是X = X +之间的差值; VS X ++ ;? [英] What's the difference between X = X++; vs X++;?
本文介绍了什么是X = X +之间的差值; VS X ++ ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你有没有试过在这之前?
Have you ever tried this before?
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
输出:10
但
static void Main(string[] args)
{
int x = 10;
x++;
Console.WriteLine(x);
}
输出:11
谁能解释为什么?
推荐答案
X ++将增加值,但随后返回其旧值。
X++ will increment the value, but then return its old value.
因此,在这种情况下:
So in this case:
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
您的X在11只一会儿,然后回来到10,因为10为(x ++)的返回值。
You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++).
您可以改为做了同样的结果:
You could instead do this for the same result:
static int plusplus(ref int x)
{
int xOld = x;
x++;
return xOld;
}
static void Main(string[] args)
{
int x = 10;
x = plusplus(x);
Console.WriteLine(x);
}
另外,值得一提的是,你将有11您预期的结果,如果你会做:
It is also worth mentioning that you would have your expected result of 11 if you would have done:
static void Main(string[] args)
{
int x = 10;
x = ++x;
Console.WriteLine(x);
}
这篇关于什么是X = X +之间的差值; VS X ++ ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文