Sub如何更新它的参数?

时间:2014-03-18 19:18:53

标签: vb.net function return call

我有一些简单的代码,我理解它的作用,但不是为什么。我有一个Sub,它会调用另一个名为Sub的{​​{1}}。 CheckIfNothing(oList)oListList(Of String) Sub会检查每个CheckIfNothing,如果是String,则会Nothing。这是代码:

""

所以在Public Function GiveList(oList As List(Of String)) CheckIfNothing(oList) Return oList End Function Public Sub CheckIfNothing(oList As List(Of String)) For Each s As String In oList If s Is Nothing Then s = "" End If Next End Sub 我致电GiveList并且我没有从CheckIfNothing返回任何内容,而CheckIfNothing中的oList仍然没有GiveList {1}} Strings

我一直认为你必须在被调用函数中返回你改变的值,并在你调用函数的子函数中再次设置值,如下所示:Nothing。在这种情况下,oList = CheckIfNothing(oList)将是一个函数。

为什么这不是必需的,这只是在VB.NET中还是在C#中?

1 个答案:

答案 0 :(得分:1)

也许这有助于解释您的问题。它来自MSDN有关Visaul Basic 2013。


将参数传递给过程时,请注意彼此交互的几个不同区别:

•底层编程元素是可修改的还是不可修改的

•论证本身是可修改的还是不可修改的

•参数是通过值传递还是通过引用传递

•参数数据类型是值类型还是引用类型

有关详细信息,请参阅Differences Between Modifiable and Nonmodifiable Arguments (Visual Basic)Differences Between Passing an Argument By Value and By Reference (Visual Basic)

此代码是一个示例,说明如何在参数周围使用()以防止其被更改。

Sub setNewString(ByRef inString As String)
    inString = "This is a new value for the inString argument."
    MsgBox(inString)
End Sub
Dim str As String = "Cannot be replaced if passed ByVal" 

' The following call passes str ByVal even though it is declared ByRef. 
Call setNewString((str))
' The parentheses around str protect it from change.
MsgBox(str)

' The following call allows str to be passed ByRef as declared. 
Call setNewString(str)
' Variable str is not protected from change.
MsgBox(str)

Passing Arguments by Value and by Reference (Visual Basic) 2013