【发布时间】:2011-07-12 19:53:22
【问题描述】:
对于这样一个基本的范围界定问题,我很抱歉,但我显然不了解非常基本的范围界定。我有一个非常简单的课程:
Public Class testListClass
' This just contains a single list that is set by a property or the constructor
Private classArrayList As New ArrayList()
Public Sub New(ByVal theList As ArrayList)
classArrayList = theList
End Sub
End Class
然后我有一个代码块,当我按下一个按钮时,它会实例化它,将一个包含三个值 (1,2,3) 的新 testListClass 对象传递给它。
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
' Lets see if changing the arrayList results in all of the testListClass items being changed
Dim theList As New List(Of testListClass)
Dim localArrayList As New ArrayList()
localArrayList.Add(1)
localArrayList.Add(2)
localArrayList.Add(3)
theList.Add(New testListClass(localArrayList))
' This results in theList.classArrayList being cleared. Why since the parameter
' to the constructor is passed by value?
localArrayList.Clear()
localArrayList.Add(10)
localArrayList.Add(20)
theList.Add(New testListClass(localArrayList))
End Sub
在“theList.Add(New testListClass(localArrayList))”调用之后,theList 包含一个“testListClass”对象,它包含三个值(1、2、3),正如我所期望的那样。以下是我不明白的。下一个电话是:
localArrayList.Clear()
如果我在调试器中设置断点并执行这一行,我看到的是:
theList(0).classArrayList 现已被清除。在 clear() 之前它包含三个值 (1,2,3),在调用清除本地定义的 arrayList 之后,“theList(0)”的内容现在已被清除。这是为什么?我认为由于 New 构造函数参数是按值传递的 (ByVal),因此在调用代码中本地更改容器值不会影响先前传递给不同类中另一个方法的值。我在这里缺少什么明显的原则?
【问题讨论】:
-
对不起标题...应该是“为什么”,而不是“什么”。在玩完这个之后,我注意到如果我克隆列表,它似乎可以正常工作。因此,如果我将“theList.Add(New testListClass(localArrayList))”更改为“theList.Add(New testListClass(localArrayList.clone))”,那么它可以工作。
-
您使用
ArrayList而不是List<T>有什么原因吗?即使它只是List<object>,它也比ArrayList更可取,因为它实现了通用集合接口。