加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#自动增量运算符错误:操作数在语法上是不正确的?

发布时间:2020-12-15 23:41:53 所属栏目:百科 来源:网络整理
导读:我正在寻找 the docs并试图了解运算符的实际工作方式. 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 ope
我正在寻找 the docs并试图了解运算符的实际工作方式.

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,但它不编译,并声明运算符必须是变量,属性或索引器:

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

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

解决方法

从 draft C# 6 language specification:

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不是“变量,属性访问或索引器访问”.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读