vb.net VB:List(Of List(Of String)) 在我更改内部列表时不断更改外部列表的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15983009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:14:59  来源:igfitidea点击:

VB: List(Of List(Of String)) keeps changing the content of the outer list when I change the inner one?

vb.netlistclear

提问by user2276378

I'm writing a program in VB, and I need to make a list of lists (I've already figured out how to do that one). The problem is, the outer list is going to need a different number of elements depending on other variables elsewhere in the program.

我正在用 VB 编写一个程序,我需要制作一个列表列表(我已经想出了如何做到这一点)。问题是,根据程序中其他地方的其他变量,外部列表将需要不同数量的元素。

I've looped this code:

我循环了这段代码:

    Dim rep As Long = 1023
    Dim items As List(Of String)
    items.Add("First Entry")
    items.Add("Second Entry")
    items.Add("Third Entry")
    items.Add("Fourth Entry")

    '(sake of argument, these are the variables
    'that will be changing vastly earlier
    'in the program, I put them in this way to simplify
    'this part of my code and still have it work)

    Dim myList As New List(Of List(Of String))
    Dim tempList As New List(Of String)

    For index = 1 To Len(rep.ToString)
        tempList.Add(items(CInt(Mid(rep.ToString, index, 1))))
    Next

    myList.Add(tempList)
    tempList.Clear()

My issue is with that last part; every time I add the tempList to myList, it's fine, but when I clear tempList, it also clears the version of tempList in myList.

我的问题是最后一部分;每次将tempList 添加到myList 时,都可以,但是当我清除tempList 时,它也会清除myList 中的tempList 版本。

myList will have a count of 1, but the list inside it has a count of 0 as soon as I clear tempList. And I have to clear tempList because I'm looping this section of code over and over, a variable number of times.

myList 的计数为 1,但是一旦我清除了 tempList,其中的列表的计数为 0。我必须清除 tempList 因为我一遍又一遍地循环这部分代码,次数不定。

Is there a way around this? Am I being a horrible noob?

有没有解决的办法?我是一个可怕的菜鸟吗?

回答by Reed Copsey

You're using the same tempListeach time, instead of making a new one.

tempList每次都使用相同的,而不是制作一个新的。

You likely need to do:

您可能需要执行以下操作:

myList.Add(tempList)
tempList = new List(Of String) ' Create a new List(Of T), don't reuse...