This is an example of discussion in the morning group.
1 Static voidMainstring[] Arg) {2 3 varp1=NewPerson{name="Zhang San"};4 varP2=NewPerson{name="John Doe"};
int i=0;5 A1 (p1,i);6 A2 (P2,ref i);7Console.WriteLine (P1. name+ "----" +i);//output Zhang San-----08Console.WriteLine (P2. name+ "----" +i);//Output Sun Six-----1
9
}
Ten
One voidA1 (stringPpp,int i) {
i++; ppp=new person{name=" Harry "}; - }void A2 (string ppp,ref int i) {
i++; PPP. Name=" magoroku "; +}
80% of old programmers in the output P1. The name was all wrong and thought it was Harry. I didn't understand it at first. The PPP of the reference type in A1 has changed, why is the output still "Zhang San"? Later the search data understood the key factor-"formal parameters and arguments are two different variables!" 】
The parameter is the argument at the time of the method declaration. PPP such as void A1 (string ppp). An argument is a parameter that is passed when a method is called. such as the P1 of A1 (p1).
Baidu knows a summary of a Daniel:
"The data transfer that occurs in a function call is one-way. That is, the value of the argument can only be passed to the parameter, and the value of the parameter cannot be passed to the argument in reverse. Therefore, during a function call, the value of the formal parameter changes, and the value in the argument does not change. 】
Because the A1 method, Ppp=new person{name= "Harry"}, the operation of the parameter PPP address changed, not the reference address of P1. This results in no effect on the P1 of the arguments.
Compare A2. The reference address for PPP and P2 is always the same. So the P1 has always had an impact.
A point of caution when using C # parameters and arguments, reference types, and value types.