In the programming process, parameter passing between functions is generally divided into two types: Value passing and address passing. The following is an analysis.
Pass Value
For example, if you use another document to pass the value, it is equivalent to copying a document. Therefore, my modifications to this document will not affect your document. If you understand this sentence, it's easy.
The following is a demo.
<Span style = "font-family: simsun; font-size: 18px;"> static void main (string [] ARGs) {// define a variable int val = 1; // call method (VAL); console. writeline (VAL); // The final output result is still 1} static void method (int I) {// This is a copy of my document // no matter how I modify it, it does not affect your I = I + 44; console. writeline (I); // The output result of my document is 45} </span>
Address reference
Another document is yours, but if we share this document with the two of us for passing the value, we can imagine that no matter which operation will affect the final display.
Ref keyword
Or the demo above. If you replace it with the ref keyword, the effect is as follows:
<Span style = "font-family: simsun; font-size: 18px;"> static void main (string [] ARGs) {// define a variable int val = 1; // call method (ref Val); console. writeline (VAL); // The final output result is 45} // call static void method (ref int I) by reference. {// The two share the document, so all the changes I made will be rendered at the end of I = I + 44;} </span>
Out keyword
Recently, the out keyword has been encountered in the re-programming process, which is equivalent to the function of ref. It is used to pass the value reference. The difference is that before the ref is passed, the document needs to be initialized. Let's take a look at the above example.
<Span style = "font-family: simsun; font-size: 18px;"> static void main (string [] ARGs) {// define a variable int val; // The difference with ref is that you can skip initialization here // call the method (out Val); console. writeline (VAL); // The final output result is 44} // call static void method (Out int I) by reference {// I = I + 44; // The error I = 44 is returned.} </span>
Differences between ref and out
First: two documents. If the ref method is used, you cannot give me an empty document, but you can allow me to leave an empty document out.
Second, using the ref method, I can directly perform operations such as + and-on the parameters, while the out method must be assigned a value before the corresponding operations can be performed.
C # out and ref parameter Modifiers