C# 中的自增 (++) 和自减 (--) 运算符是什么?

csharpprogrammingserver side programming更新于 2025/10/14 4:52:17

增量运算符

在 C# 中,要增加一个值,可以使用增量运算符,即预自增运算符和后自增运算符。

下面是一个例子 −

示例

使用 System;

class Demo {
   static void Main() {
      int a = 250;
      Console.WriteLine(a);

      a++;
      Console.WriteLine(a);

      ++a;
      Console.WriteLine(a);

      int b = 0;
      b = a++;
      Console.WriteLine(b);
      Console.WriteLine(a);

      b = ++a;
      Console.WriteLine(b);
      Console.WriteLine(a);
   }
}

减量运算符

在 C# 中,要减少一个值,可以使用减量运算符,即预减量运算符和后减量运算符。

下面是一个例子 −

示例

using System;

class Demo {
   static void Main() {
      int a = 250;
      Console.WriteLine(a);

      a--;
      Console.WriteLine(a);

      --a;
      Console.WriteLine(a);

      int b = 0;
      b = a--;
      Console.WriteLine(b);
      Console.WriteLine(a);

      b = --a;
      Console.WriteLine(b);
      Console.WriteLine(a);
   }
}

相关文章