简体   繁体   English

“count ++”在C#中返回什么?

[英]What does “count++” return in C#?

Just ran into a bit of code that wasn't doing what I thought it should. 刚碰到一些没有按我认为应该做的代码。 Do other people think this should return 1? 其他人认为这应该返回1吗? Is there a good explanation as to why it doesn't?? 有没有一个很好的解释为什么它不?

int count = 0;

count++.ToString(); // Returns 1 no?

I always thought count++ was the same as count = count + 1... 我一直以为count ++与count = count + 1相同......

x++ is a post increment operator. x++是一个增量运算符。 It means that the value of x is incremented, but the old (non-incremented) value of x is returned (0 in your case, to which ToString is applied). 这意味着x的值递增,但返回x (非递增)值(在您的情况下为0,应用ToString )。

To get the behavior you want, use the pre increment operator ++x . 要获得所需的行为,请使用增量运算符++x

At least four of the answers posted so far are wrong. 至少到目前为止发布的答案中有四个是错误的。 It is an extremely common error to believe that the ++ operator has the same ill-defined semantics as it does in C. It does not. 认为++运算符具有与C中相同的错误定义语义是一个非常常见的错误。 它没有。 The semantics of the ++ operator are well-defined, and are quite different from how they have been described by the incorrect answers here. ++运算符的语义是明确定义的,并且与这里的错误答案描述它们的方式完全不同。 See my answer to the last time this question was asked for details: 请参阅我上次回答此问题的答案:

What is the difference between i++ and ++i? i ++和++ i有什么区别?

x++ is post increment; x ++是后增量; the current value (0) is used as the result, then the ++ happens. 当前值(0)用作结果,然后++发生。

A bit like: 有一点像:

var tmp = count;
count++;
Consle.WriteLine(tmp);

The pre-increment (++x) would behave as you expected. 预增量(++ x)将按预期运行。

(++i).ToString();

完全符合你的期望。

Your original code will always show 0. 您的原始代码将始终显示为0。

Try this: 试试这个:

(++c).ToString();

This will return 1. 这将返回1。

From the MSDN site : 从MSDN站点

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. 操作的结果是操作数增加之前的值。

No, ++count return "1". 不,++计数返回“1”。 count++.ToString() execute the ToString() method and then increments count, so it returns "0". count ++。ToString()执行ToString()方法,然后递增计数,因此返回“0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM