【发布时间】:2020-07-05 08:39:26
【问题描述】:
如果您需要增加超过 1,您可以在循环中多次写入 example++;,但是如果我需要增加 100 左右怎么办?有没有办法让它乘以或增加超过 1? (除了在 Console.WriteLine 中相乘)
【问题讨论】:
-
你的意思是
example = example + 100; -
example += 100;会这样做吗?
标签: c#
如果您需要增加超过 1,您可以在循环中多次写入 example++;,但是如果我需要增加 100 左右怎么办?有没有办法让它乘以或增加超过 1? (除了在 Console.WriteLine 中相乘)
【问题讨论】:
example = example + 100;
example += 100; 会这样做吗?
标签: c#
根据彼得的评论:
example += 100;
意思相同
example = example + 100;
这称为复合分配,有many operators 以这种方式完成工作,例如
example -= 100;
example *= 100;
有关完整列表,请参阅上面链接的 MSDN
c# 中的任何赋值都会返回赋值,因此它可以用作更大语句的一部分。 += 也不例外,这将打印“x incremented is 101”:
int x = 1;
Console.WriteLine("x incremented is " + (x+= 100));
唯一值得注意的是++以两种形式存在,x++或++x——第一种形式返回x增加之前的值,第二种形式返回之后的值。
int x = 1;
Console.WriteLine("x incremented is " + (x++)); //x is now 2 but the message says it is 1
Console.WriteLine("x incremented is " + (++x)); //x is now 3 and the message says it is 3
+= 只返回递增后的值。在您向其添加 100 之前没有返回 x 的表单
【讨论】:
将示例值增加 x 的最简单解决方案是 example=example+x。这更易读,但是您可以使用缩写形式 example+=x。
【讨论】: