VB return 值

VB return value

我目前正在将一些代码从 VB6.0 迁移到 VB.NET 并注意到一个问题。我是 VB6.0 的新手,现在我知道可以通过以下方式返回多个值:

Function test(str1 As String, str2 As String) As Long

str1 = "Hello World1"
str2 = "Hello World2"

test = 0

End Function

当我调试时,我可以看到传递的参数现在已更新。但是我的问题是 VB.NET 似乎没有这样做。我如何在 VB.NET 中执行此操作?

如有任何建议,我们将不胜感激。

在 VB6 中,参数默认通过引用传递,而在VB.NET中,它们通过默认值。这就解释了为什么它的行为不同。如果要保留旧行为并通过引用传递参数,则需要明确说明(注意附加的 ByRef 关键字):

Function test(ByRef str1 As String, ByRef str2 As String) As Long

str1 = "Hello World1"
str2 = "Hello World2"

test = 0 'don't forget to migrate this line to VB.NET as well

End Function

在 VB.NET 中,默认的参数传递方式是按值 (ByVal) 而不是按引用 (ByRef)。要获得 VB 6 行为,您需要使参数 ByRef:

Function test(ByRef str1 As String, ByRef str2 As String) As Long

  str1 = "Hello World1"
  str2 = "Hello World2"

  Return 0

End Function

在VB 6 中默认是通过引用,因为按值传递参数的成本更高,因为需要复制对象。在 VB.NET 中,默认值是按值传递的,因为不需要复制对象,而是将对象的引用作为参数值传递。

在 VB.NET 中,您还可以使用 Return 语句来 return 值。 (请注意,它会退出函数,而将值赋给函数名不会。)