链增量运算符

Chain Increment Operators

为什么不能连锁经营?

int test = 5;
test++++;

int test = 5;
++test++;

此代码给出编译时错误。

The operand of an increment or decrement operator must be a variable, property or indexer.

我完全理解这一点,如果允许,那将是一个完整的代码味道,几乎没有实际使用。我不完全理解为什么这会导致错误。我几乎希望每个语句后 test 的值是 7。

++ 运算符在 "left hand value" 上工作,即可以分配给的东西,因为它等同于:

test = test + 1;

另一方面 test++ 是一个表达式,你不能给它赋值,test++ = 5 不起作用。

这就是(test++) ++不起作用的原因。

++ 是一个特殊的运算符,它只是 foo = foo + 1 的 shorthand。创建无限的重载列表(如 +++、++++ 等)毫无意义,当您可以只说 foo = foo + 7,这是必须要做的。

  • 本身是一个连接 2 个值的运算符。如果语言设计者试图像您建议的那样将 pull double duty 作为一种特殊语法,那将给编译器带来额外的负担,并可能导致一些混乱的代码。

所以基本上简短的回答是不值得付出努力。没有它并不难,尤其是使用 += 运算符。而且它更具可读性。什么更容易阅读:

int test = 1;
test+++++;

或者....

int test = 1;
test += 5;

数一数所有这些加号会让人难以阅读。 2 清晰可见。不仅如此,您还可以在 50-50 的抽奖活动中数软心豆粒糖。 :-)

基本上,这是由于规范的第 7.6.9 节:

The operand of a postfix increment or decrement operation must be an expression classified as a variable, a property access, or an indexer access. The result of the operation is a value of the same type as the operand.

第二句意味着 i++ 被归类为 (不是变量,不像 i)并且第一句阻止它被分类运算符的操作数。

我怀疑它是为了简单而设计的,以避免您真的不想进入的奇怪情况 - 不仅仅是您提供的代码,还有诸如:

Foo(ref i++);
i++ = 10;