2013-04-13 109 views
2

我正在寫一個VB程序,我需要列出一個列表(我已經想出瞭如何做到這一點)。問題是,根據程序中其他位置的變量,外部列表將需要不同數量的元素。VB:List(Of List(Of String))當我更改內部列表時,會不斷更改外部列表的內容?

我循環驗證碼:

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() 

我的問題是與最後一部分;每當我將tempList添加到myList中時,它都可以,但是當我清除tempList時,它也會清除myList中tempList的版本。

myList將會有1的計數,但是隻要我清除了tempList,它裏面的列表就有一個計數0。而且我必須清除tempList,因爲我反覆循環這段代碼的次數是可變的。

有沒有辦法解決這個問題?我是一個可怕的菜鳥嗎?

+0

唔,'tempList'是一個對象_reference_,沒有它,當你將它添加到'myList'對象的額外的「版本」。當時還有一個額外的對象引用,但引用指向同一個對象(List)。你爲什麼要清除它? –

+0

對不起 - 我錯過了你向我們展示了一個循環的內部。 –

回答

2

您每次都使用相同的tempList,而不是創建一個新的。

你可能需要做的:

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

是的!這工作完美。非常感謝! – user2276378

+0

@ user2276378請參閱http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235 –

相關問題