2015-06-28 53 views
-3

我一直在试图理解C#refout之间的差异,面临的a++++a这种误解。A ++没有在C#程序增加

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 
    } 
} 

任何人都可以解释为什么a++没有增加到5在上述代码。

回答

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增量,新值将传递到方法中。

+0

可你检查你的代码,我想你指的是第一个'+了'应该是一个''+向右? –

+1

检查出[这里](http://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-andi-i)@HassanNahhal –

+0

@ M.kazemAkhgary非常感谢,我检查了所有问题,有一个人说,答案错误,声誉很高,我读了他的答案,但很难理解。 –

1

a ++被评估然后分配。但++ a被赋值然后被评估。

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

i = ++a; 
// i = a 
// a = a + 1 
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 
2

从文档上++ operator

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

所以,你的代码向外扩张看起来更像这个

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. 
}