为什么VB.NET在列表中表现如此?

时间:2012-09-02 20:19:57

标签: vb.net list nested-lists

这是一个关于列表清单的问题。

    Dim smallList As New List(Of Integer)
    Dim largeList As New List(Of List(Of Integer))

    smallList.Add(3)
    largeList.Add(smallList)
    smallList.Clear()
    smallList.Add(4)
    largeList.Add(smallList)

在这段代码中,我希望largeList将list(3)添加到自身,然后将list(4)添加到自身。但是不是将数据存储在smallList中,而是似乎存储了一个引用smallList,因此最终包含((4),(4)),这不是我想要的。

为什么会这样做,我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:2)

当您有一个引用类型列表时,实际上有一个引用列表。向列表中添加内容并不意味着数据被复制,而只是添加到列表中的引用。

要将单独的对象添加到列表中,您必须为每个项目创建一个新对象,并且列表也是引用类型本身,也适用于列表。

Dim smallList As List(Of Integer) ' just a reference at this time
Dim largeList As New List(Of List(Of Integer))

smallList = New List(Of Integer)() ' The first list
smallList.Add(3)
largeList.Add(smallList)
smallList = New List(Of Integer)() ' Here's another list
smallList.Add(4)
largeList.Add(smallList)
相关问题