C# 自动递增运算符错误:操作数在语法上不正确? [英] C# auto-increment operator error: Operand is not syntactically correct?

查看:42
本文介绍了C# 自动递增运算符错误:操作数在语法上不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看文档 并试图了解运算符的实际工作方式.

I'm looking at the docs and trying to understand how the operator actually works.

增量运算符 (++) 将其操作数加 1.增量运算符可以出现在其操作数之前或之后:++variablevariable++.

The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand: ++variable and variable++.

第一种形式是前缀递增操作.操作的结果是操作数递增后的值.

The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

第二种形式是后缀自增操作.操作的结果是操作数递增前的值.

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.

我希望以下操作返回 3,但它不会编译,并声明操作符必须是变量、属性或索引器:

I would expect the following operation to return 3, but it doesn't compile, and states the operator must be a variable, property or indexer:

int x = 0;
Console.WriteLine(x++ ++ ++);
/*Expected output: 3*/

为什么不对?我是否应该假设 x++ 不为下一个 ++ 运算符返回相同类型的值?

Why is that wrong? Should I assume x++doesn't return a value of the same type for the next ++ operator?

推荐答案

来自 草案 C# 6 语言规范:

后缀递增或递减操作的操作数必须是分类为变量、属性访问或索引器访问的表达式.操作的结果是一个与操作数相同类型的值.

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.

x 是一个变量,但 x++ 不是变量、属性访问或索引器访问."

x is a variable, but x++ is not a "variable, property access, or an indexer access."

现在,让我们想象一个这样的后缀增量运算符调用合法的世界.给定一个 int x = 42;x++x 增加到 43,但计算结果为 42.如果 x++ ++ 是合法的,它将适用于 x++,这不是您想要的(它会增加临时值,而不是 x)

Now, let's imagine a world where such postfix increment operator call would be legal. Given an int x = 42;, x++ increments x to 43, but it evaluates to 42. If x++ ++ was legal, it would apply to the x++, which isn't what you want (it would increment the temporary, not x)

这篇关于C# 自动递增运算符错误:操作数在语法上不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆