你以前试过这个吗?
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++ 将递增该值,但随后返回其旧值。
所以在这种情况下:
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
X 暂时为 11,然后它又回到 10,因为 10 是 (x++) 的返回值。
您也可以这样做以获得相同的结果:
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 的预期结果:
static void Main(string[] args)
{
int x = 10;
x = ++x;
Console.WriteLine(x);
}
关于c# - X = X++; 有什么区别?与 X++;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574006/