开发者

Why does List.Clear() also get rid of a class property?

I have the following class:

    Public Class ID
        Private sID as List(Of Integer)

        Public property IDlist as List(Of Integer)
            Get
                Return sID
            End Get
            Set(ByVal value as List(Of Integer)
                sID = value
            End Set
        End Property
    End Class

I then do:

    Dim objID as ID
    Dim myList as List(Of Integer)

    for i = 0 to 1
        objID = New ID
        MyList.add(1)
        Mylist.add(2)

        ID.IDlist = mylist
        mylist.clear
    Next

If I insert code to retrieve one of the ID.IDlist properties BEFORE mylist.clear it works fine for both iterations. However, if I try to retrieve the values AFTER the for loop I get nothing.

I found that this code allows me to get the ID.IDlist for both ID objects after for for loop:

    Dim objID as ID
    Dim myList as List(Of Integer)

    for i = 0 to 1
        objID = New ID
        mylist = New List(Of Integer)

        MyList.add(1)
        Mylist.add(2)

        ID.IDlist = mylist
    Next

I could be way off here, but it almost seems like ID.IDlist points to the address of mylist and so when mylist is cleared so is ID开发者_运维百科.Idlist. It seems as though the reason the second block of code works is because I am creating a new list in memory for each ID object and ID.IDlist just points to it... is that right?

Can anyone confirm / explain? I spent like 5 hours on this situation.. ugh

thank you for any explanation!


Yes you are passing a reference type which means that you are creating a copy of the pointer to the object in the stack.

To prevent this you can make a shallow copy of the list. In this case that would be easy by using the Extension method ToList().

objId.IDlist = myList.ToList()


When you do: ID.IDlist = mylist

Both ID.IDlist and mylist are the exact same list. If you clear one, you also clear the other.

Also, I don't think this will compile since ID is a class and not an object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜