是否有可能:将index增加1,然后在1行代码内换回0 if(index> list.Count)? [英] Is it possible to: increment index by 1 and wrap back to 0 if(index > list.Count) within 1 line of code?
问题描述
我现在正在做什么:
index++;
index %= list.Count;
我想将它们合并为1条快速线,例如:
I want to merge them into 1 quick line, something like:
++index %= list.Count;
但是编译器不允许我这样做.
But the compiler is not allowing me to.
我想知道:
- 是否可以将这2条合并为1条快速易读的行?
- 说明为什么我的工作不起作用,IIRC我一直在C/C ++中一直这样做
感谢您的时间!
推荐答案
如果第一个版本在C或C ++中运行,我会有点感到惊讶,但是这确实让我感到惊讶.它在C#中不起作用的原因是%=
运算符的左侧必须是变量,而表达式 ++ index
不是分类为变量-它是一个值.
I'd be slightly surprised if the first version worked in C or C++, but then it does surprise me quite often. The reason it doesn't work in C# is that the left-hand side of the %=
operator has to be a variable, and the expression ++index
isn't classified as a variable - it's a value.
尽管如此,我还是不会将其称为易于阅读"的行.很容易理解的是:
I wouldn't call it an "easy to read" line anyway though. What is pretty simple to understand is this:
index = (index + 1) % list.Count;
完全不需要复合赋值运算符.
No need for a compound assignment operator at all.
这篇关于是否有可能:将index增加1,然后在1行代码内换回0 if(index> list.Count)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!