C# 中的单行增量和返回语句
过去几天一直在使用 C# 并试图利用它的“简洁”语法,我尝试使用以下技巧。
Int32 _LastIndex = -1;
T[] _Array;
_Array[_LastIndex++] = obj;
现在的问题是它在增加数字之前返回值,所以我尝试了......
_Array[(_LastIndex++)] = obj;
但同样的行为正在发生(这也让我有点困惑)。
有人可以首先解释为什么第二个例子(我理解为什么第一个)不起作用吗?有什么方法可以完成我想做的事情吗?
Having been playing around with C# the last few days and trying to take advantage of its "succinct" syntax I have tried to use the following trick.
Int32 _LastIndex = -1;
T[] _Array;
_Array[_LastIndex++] = obj;
Now the problem with this is that it returns the value prior to incrementing the number, so I tried...
_Array[(_LastIndex++)] = obj;
And yet the same behavior is occurring (Which has also got me a bit confused).
Could someone firstly explain why the second example (I understand why the first) doesn't work? And is there some way of accomplishing what I am trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用括号将后自增
_LastIndex++
括起来并不会将其分隔为不同的操作,它只是将: 更改为:
如果要在使用前自增,则需要预自增变体,如下所示:
Surrounding the post-increment
_LastIndex++
with parentheses doesn't separate it into a distinct operation, it just changes:into:
If you want to increment before use, you need the pre-increment variant, as follows:
您是否尝试过
_Array[++_LastIndex]
。LastIndex++
增加值但返回旧值。++LastIndex
递增并返回递增的值。Have you tried
_Array[++_LastIndex]
.LastIndex++
increments the value but returns the old value.++LastIndex
increments and returns the incremented value.您想要:
这称为预增量,这意味着增量发生在使用值之前。括号用于修改优先级,不一定改变计算顺序。此外,在这种情况下,括号对优先级没有影响。
You want:
This is called pre-increment, which means the increment takes place before the value is used. Parentheses are used to modify precedence, not necessarily change the order of evaluation. Further, the parentheses had no effect on the precedence in this instance.