gpt4 book ai didi

vb.net - Sub 如何更新它的参数?

转载 作者:行者123 更新时间:2023-12-05 05:27:00 25 4
gpt4 key购买 nike

我有一些简单的代码,我明白它的作用但不知道为什么。我有一个 Sub,它调用另一个名为 CheckIfNothing(oList)SuboList 是一个 List(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 返回任何东西,而且 oListGiveList 中没有 StringsNothing

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

为什么这不是必需的,这仅在 VB.NET 中还是在 C# 中也是如此?

最佳答案

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


将参数传递给过程时,请注意几个相互影响的不同区别:

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

•参数本身是可修改的还是不可修改的

•参数是按值还是按引用传递

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

有关详细信息,请参阅 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

关于vb.net - Sub 如何更新它的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22488983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com