Possible Duplicate:
Difference betw开发者_StackOverflow中文版een ref and out parameters in .NET
I know that ref is used for passing the changed value of the variable outside of the function, but how is it different from out?
An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
An out
parameter must be assigned before it can be read and before the function returns.
A ref
parameter does not need to be assigned to before it's read or the function returns.
Consequently, a variable must be assigned before passing it in as a ref
parameter, while an out
parameter may be uninitialized before passing it in.
A ref
parameter allows you to pass data in to your function in addition to sending it out.
A function with an out
parameter cannot see the parameter's initial value (the compiler considers it uninitialized)
Specifying a parameter as out
means that the function is required to assign a value to it before it returns. Specifying a parameter as ref
means that a function can assign a value to it, but is not required to.
Note that this is just a C# convention and the runtime makes no distinction between the two.
ref
is used when the value of the variable going into the method is considered to be initialized and ready to be used. An example is an index in a string parsing system: a method can have a ref int index
that will be incremented based on what the method reads.
out
is analogous to multiple return values. The variable does not have to be initialized before calling the method, and the variable must be set in the called method before it returns.
精彩评论