gpt4 book ai didi

vb.net - List(T) 的对象是通过 ByVal 还是 ByRef 传递有关系吗

转载 作者:行者123 更新时间:2023-12-03 00:31:29 33 4
gpt4 key购买 nike

在下面的示例中,我是否在 ByRef 或 ByVal 函数中传递 List(T) 对象有关系吗?

这是对的吗,因为List是引用类型,所以即使我传递对象ByVal,值也总是会改变。

如果我在更新列表时在函数“ListChanged”中传递对象 byRef 会更好吗?

Public Class MyClass_

Public Sub TestMethod()

Dim List_1 As New List(Of Integer)()
Dim List_2 As New List(Of Integer)()

List_1.Add(100)
List_2.Add(50)

List_1 = ActualListNotChanged(List_1) '---101
List_2 = ListChanged(List_2) '---50,51

End Sub


Private Function ActualListNotChanged(ByVal lst As List(Of Integer)) As List(Of Integer)

Dim nList As New List(Of Integer)()

For Each item As Integer In lst
If item <> 50 Then
nList.Add(101)
End If
Next item

Return nList

End Function

Private Function ListChanged(ByVal lst As List(Of Integer)) As List(Of Integer)

lst.Add(51)
Return lst

End Function

End Class

最佳答案

在您的示例中,ByVal(默认值)是最合适的。

ByVal 和 ByRef 都允许您修改列表(例如添加/删除项目)。ByRef 还允许您用不同的列表替换该列表,例如

Dim List1 As New List(Of Int)
List1.Add(1)
ListReplacedByVal(List1)
' List was not replaced. So the list still contains one item
Debug.Assert(List1.Count = 1) ' Assertion will succeed

ListReplacedByRef(List1)
' List was replaced by an empty list.
Debug.Assert(List1.Count = 0) ' Assertion will succeed


Private Sub ListReplacedByVal(ByVal lst As List(Of Integer))
lst = New List(Of Int)
End Sub

Private Sub ListReplacedByRef(ByRef lst As List(Of Integer))
lst = New List(Of Int)
End Sub

一般来说,您应该使用 ByVal。您传递的对象可以被修改(从某种意义上说,您可以调用其方法和属性 setter 来更改其状态)。但它不能被其他对象替换。

关于vb.net - List(T) 的对象是通过 ByVal 还是 ByRef 传递有关系吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19953614/

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