我看到它们都在大量的c#代码中使用,我想知道什么时候使用i++或++ I (I是一个数字变量,如int, float, double等)。有人知道吗?
当前回答
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
这是否回答了你的问题?
其他回答
如果你有:
int i = 10;
int x = ++i;
那么x等于11。
但如果你有:
int i = 10;
int x = i++;
那么x等于10。
注意,正如Eric指出的那样,在这两种情况下,增量同时发生,但不同的是作为结果给出的值(谢谢Eric!)
通常,我喜欢使用++ I,除非有很好的理由不这样做。例如,在编写循环时,我喜欢使用:
for (int i = 0; i < 10; ++i) {
}
或者,如果我只需要增加一个变量,我喜欢使用:
++x;
通常情况下,一种方式或另一种方式并没有太大的意义,而是归结于编码风格,但如果您在其他赋值中使用运算符(就像我最初的示例一样),那么了解潜在的副作用是很重要的。
操作符的工作方式是它同时被加1,但如果它在变量之前,表达式将用加1 /减1的变量求值:
int x = 0; //x is 0
int y = ++x; //x is 1 and y is 1
如果它在变量之后,则当前语句将与原始变量一起执行,就好像它还没有被加/减:
int x = 0; //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
除非必要,我同意dcp使用预递增/递减(++x)。实际上,我唯一一次使用后递增/递减是在while循环或类似的循环中。这些循环是相同的:
while (x < 5) //evaluates conditional statement
{
//some code
++x; //increments x
}
or
while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
//some code
}
你也可以在索引数组时这样做:
int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
等等,等等……
我想我会用代码来回答这个问题。想象一下int的以下方法:
// The following are equivalent:
// ++i;
// PlusPlusInt(ref i);
//
// The argument "value" is passed as a reference,
// meaning we're not incrementing a copy.
static int PlusPlusInt(ref int value)
{
// Increment the value.
value = value + 1;
// Return the incremented value.
return value;
}
// The following are equivalent:
// i++;
// IntPlusPlus(ref i);
//
// The argument "value" is passed as a reference,
// meaning we're not incrementing a copy.
static int IntPlusPlus(ref int value)
{
// Keep the original value around before incrementing it.
int temp = value;
// Increment the value.
value = value + 1;
// Return what the value WAS.
return temp;
}
假设你知道ref是如何工作的,这应该很好地解决了这个问题。在我看来,用英语解释它要笨拙得多。
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
这是否回答了你的问题?
只是为了记录,在c++中,如果你可以使用任何一种(即),你不关心操作的顺序(你只想增加或减少,然后再使用它),前缀操作符更有效,因为它不需要创建对象的临时副本。不幸的是,大多数人使用posfix (v++)而不是prefix (++var),因为这是我们最初学到的。(我在一次采访中被问到这个问题)。不确定这在c#中是否正确,但我假设它是正确的。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和