Today while browsing Bowen, see this article: C # ref pass in and out in the end what is? Use questions at the time of transfer target ref
Attached words:
Network is a day off, now home only then release it.
Have we all know, is to pass a reference type on the address, the type of value passed is the value, but also so many people are still confused, although circulated on the Internet a lot of related articles ref, everyone did not seem to take off his confusion.
I was recently looking at CYQ.Data framework of time talking about, since class is a reference to an address, the address itself is the pass, you have to write code to do ref transfer;
The original previously understand, been fooled do not understand what changed, he thought he was the original code was wrong.
When doubts today to help people, and only then their confusion to understanding.
Here I put the code on the articles of the original problem of small changes a bit
Posted do Example:
// output is Wangwu
the Console.ReadKey ();
}
static void Change (the Person P) { P = new new the Person ( " John Doe " ); } static void Change (the Person P, String name) { p.Name = name ; } static void Change ( REF the Person P) { P = new new the Person ( " Wang Wu " ); } }
Screenshot let everyone look at the way here is how the debugging and doubts.
F5 to run:
1: We run to the first line of code, breakpoints:
2: We run to (p) of the Internal Change
Remark p value changed, it is not performed due to a breakpoint instantiated at a first line of code, so the values are the same.
Thus the first row in the result output: Zhang
3: run next to Change (p, "John Doe") internal function
but it points to the value is the same, so you put the value changed, so "John Doe" came out.
Note: internal and outside p p although not the same, but the point is the same value .
Thus the first row in the result output: John Doe
4: Finally Change (ref p) internal function
Then redirected to a new object, but the value of the object's address has changed.
Note: the external address p = p internal address, which points to the values are values of the new object.
The third row then outputs the result: Zhang
The end result is as follows:
Last knot words:
So, do not realize the type of reference only pass the address of a value type by value on the matter, to be honestly noted that, when the type of pass-by-reference, inside pass participants generate a new address.
So when we passed class reference, I prefer to use the new in-house migrant workers have to pay attention to pay attention.
Reproduced in: https: //my.oschina.net/secyaher/blog/274342