问题描述
我有一个带有字符串数组作为参数的 Sub:
I have a Sub with an array of strings as parameter:
Private Sub des(ByVal array() As String)
Dim i As Integer
For i = 0 To UBound(array)
array(i) = "hy"
Next
End Sub
当我在主函数中调用该函数时,即使将数组传递给函数 ByVal,str 的值也会发生变化:
When I call the function inside my main function, the value of str changes even if the array is passed to the function ByVal:
Dim str() As String
str = {"11111", "22222", "33333", "44444", "5555", "66666"}
des(str)
我尝试在 Sub 中复制数组,但它仍然在主函数中发生变化.
I tried making a copy of the array in the Sub, but it still changes in the main function.
Private Sub des(ByVal array() As String)
Dim i As Integer
Dim array2() As String
array2 = array
For i = 0 To UBound(array)
array(i) = "hy"
Next
End Sub
我在一个网站上读到你不能通过数组 ByVal.这是真的?如果是这样,我应该如何进行?
I read on a site that you cannot pass arrays ByVal. Is this true? If so, how should I proceed?
推荐答案
不,这不是真的.
.NET 框架中的数组是引用类型.创建数组时,将创建一个System.Array
对象,并将其引用分配给引用变量.
An array in the .NET framework is a reference type. When you create an array, an object of System.Array
will be created and its reference is assigned to the reference variable.
当你调用一个 des
方法时,会传递数组对象的引用.在des
方法中,ByVal参数是一个System.Array
类型的引用参数变量,它接收一个数组对象的引用副本.
When you call a des
method, the reference of the array object will be passed. In des
method, ByVal parameter is a reference parameter variable of type System.Array
, and it receive a copy of reference of an array object.
MSDN 文章 - 按值和按引用传递参数(可视化基本)
MSDN article - Passing Arguments by Value and by Reference (Visual Basic)
这篇关于子/函数数组参数改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!