c# - X = X++; 有什么区别?与 X++;?

标签 c#

你以前试过这个吗?

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/

相关文章:

c# - 带有 Fellow-oak DICOM 的 Xamarin 不会在 bin 文件夹中创建 DicomNative.dll

c# - ILogger 不遵守 Application Insights 的日志级别

c# - 同时编写和验证 XML

c# - 除以两个整数不返回预期结果

c# - 基于授权的 ASP.Net Web Api 帮助页面

c# - 如何从 C# 访问 Excel VBA 中的类模块?

c# - WPF 绑定(bind)源

c# - C#中如何删除不在栈顶的栈项

c# - C#获取当前位置的经纬度

c# - 映射到 Nhibernate 中的枚举位标志