a ++没有在C#程序中增加

时间:2015-06-28 00:04:54

标签: c#

我一直试图了解ref之间的区别  和#{1}}在C#中遇到了对outa++的误解。

++a

任何人都可以解释为什么class Program { static void Main ( string [] args ) { int a = 3; incr ( a ) ; Console.ReadKey (); } public static void incr ( int a ) // a = 3 { Console.WriteLine (++a); // a incremented to 4 Console.WriteLine ( a++ ); // a should be incremented to 5 , but it is still 4 } } 在上面的代码中没有增加到5。

4 个答案:

答案 0 :(得分:4)

public static void incr (int a ) // a = 3
{
    Console.WriteLine (++a); // Pre-Increment:  Increment to 4 and pass it in.
    Console.WriteLine (a++); // Post-Increment: Increment to 5, but use the old value (4).
    Console.WriteLine (a);   // Will show 5
}

问题是a++将增加到5,但它会在增加之前使用参数的旧值。 ++a递增,新值将传递给方法。

答案 1 :(得分:2)

来自++ operator

的文档
  

第一种形式是前缀增量操作。结果   operation是操作数增加后的值   第二种形式是后缀增量操作。结果   operation是操作数增加之前的值。

所以扩展的代码看起来更像是

public static void incr (   int a ) // a = 3
{
    int aResult;

    //++a
    a = a + 1; // a = 4
    aResult = a; //aResult = 4
    Console.WriteLine (aResult ); //  prints 4

    //a++
    aResult = a; //aResult = 4
    a = a + 1; //a = 5
    Console.WriteLine (aResult); // prints 4 because the result was copied before the increment.
}

答案 2 :(得分:1)

评估a ++然后分配。但是++ a被分配然后被评估。

i = a++;
// a = a + 1;
// i = a

i = ++a;
// i = a
// a = a + 1

答案 3 :(得分:0)

这是前后增量。

++p - 预增量将首先递增,然后将显示在控制台输出

p++将首先显示在控制台中,然后会增加,因此您将得到结果。

所以,在你的情况下

Console.WriteLine (++a); // a incremented to 4
Console.WriteLine ( a++ ); // it will display 4
Console.WriteLine ( a ); // it will be 5 this time