开发者

Why is list.add() adding items to object AND source object as well?

Hopefully this is simple enough. I need to be able to add elements to a copy of mylist.testlist without modifying the global mylist object. (Which seems to be happening via the below code.)

When I am working on x, which should be a totally separate object, mylist is getting modified as well. How can I fix this? I have worked with lists extensively and never seen this behavior before. I have tested and reproduced the problem in .NET 3.5 and .NET 4.0 on Win 7 Pro 32bit.

TIA!

Source Code:

Public Class Form1
    Public mylist As New test

    Sub Main()
        Dim x As test = mylist
        For i As Integer = 0 To 10
            x.testlist.Add(False)
        Next

        MsgBox("x count: " + x.testlist.Count.ToString + vbCrLf + "mylist count: " + mylist.testlist.Count.ToString)

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Main()
    End Sub
End Class
Public Class test
    Public testlist As New List(Of Boolean)
    Public Sub New()
        testlist.Add(F开发者_StackOverflow社区alse)
    End Sub

End Class


As Tim Schmelter pointed out in his comment, your problem is the line:

Dim x As test = mylist

by which x gets a reference to mylist. That means both (x and mylist) are pointing to the same instance of test. That's why changing one of them is changing the other too.

To fix it, you could define x as a new instance of test and copy all elements from mylist.testlist to x.testlist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜