VB.Net 的参数传递机制有两种方法:ByVal 和 ByRef。ByVal 就是 By Value 的意思,ByRef 就是 By Reference 的意思。
比如下面的例子,函数 Display 提供参数 x 给函数 ToIncrement,调用 ToIncrement。
用 ByVal 的返回结果是:x=5 y=2
用 ByRef 的返回结果是:x=1 y=2
Private Sub Display()
Dim x As Integer = 5
Dim y As Integer = ToIncrement(x)
MsgBox("y=" & y & " x= " & x, MsgBoxStyle.OkOnly)
End Sub
Private Function ToIncrement(ByVal number As Integer) As Integer
number = 1
Return number + 1
End Function
下面是 MSDN 的解释:
When you pass one or more arguments to a procedure, each argument corresponds to an underlying programming element in the calling code. You can pass either the value of this underlying element, or a reference to it. This is known as the passing mechanism.
You pass an argument by value by specifying the ByVal keyword for the corresponding parameter in the procedure definition. When you use this passing mechanism, Visual Basic copies the value of the underlying programming element into a local variable in the procedure. The procedure code does not have any access to the underlying element in the calling code.
You pass an argument by reference by specifying the ByRef keyword for the corresponding parameter in the procedure definition. When you use this passing mechanism, Visual Basic gives the procedure a direct reference to the underlying programming element in the calling code.
The choice of passing mechanism is not the same as the classification of the underlying element type. Passing by value or by reference refers to what Visual Basic supplies to the procedure code. A value type or reference type refers to how a programming element is stored in memory.
However, the passing mechanism and element type are interrelated. The value of a reference type is a pointer to the data elsewhere in memory. This means that when you pass a reference type by value, the procedure code has a pointer to the underlying element's data, even though it cannot access the underlying element itself. For example, if the element is an array variable, the procedure code does not have access to the variable itself, but it can access the array members.
When you pass a nonmodifiable element as an argument, the procedure can never modify it in the calling code, whether it is passed ByVal or ByRef.
For a modifiable element, the following table summarizes the interaction between the element type and the passing mechanism.
| Element type | Passed ByVal | Passed ByRef |
| Value type (contains only a value) | The procedure cannot change the variable or any of its members. | The procedure can change the variable and its members. |
| Reference type (contains a pointer to a class or structure instance) | The procedure cannot change the variable but can change members of the instance to which it points. | The procedure can change the variable and members of the instance to which it points. |
上一页: 值类型 (Value Types)和引用类型 (Reference Types)的区别 返回上级目录: VB.NET 的参数传递机制 下一页: 用 ByVal 还是用 ByRef 传递参数?
© 2008 HubaPo.com 版权所有 Contact me