开发者

Generic Lists copying references rather than creating a copiedList

开发者 https://www.devze.com 2022-12-22 10:29 出处:网络
I was developing a small function when trying to run an enumerator acros开发者_高级运维s a list and then carry out some action. (Below is an idea of what I was trying to do.

I was developing a small function when trying to run an enumerator acros开发者_高级运维s a list and then carry out some action. (Below is an idea of what I was trying to do.

When trying to remove I got a "Collection cannot be modified" which after I had actually woken up I realised that tempList must have just been assigned myLists reference rather than a copy of myLists. After that I tried to find a way to say

tempList = myList.copy

However nothing seems to exist?? I ended up writing a small for loop that then just added each item from myLsit into tempList but I would have thought there would have been another mechanism (like clone??)

So my question(s):

  • is my assumption about tempList receiving a reference to myList correct
  • How should a list be copied to another list?

        private myList as List (Of something)
    
    sub new()
        myList.add(new Something)
    end sub
    
    sub myCalledFunction()
        dim tempList as new List (Of Something)
        tempList = myList
        Using i as IEnumerator = myList.getEnumarator
           while i.moveNext
               'if some critria is met then 
               tempList.remove(i.current)
           end
        end using
    
    end sub
    


By writing tempList = myList you don't make a copy oh the collection, you only make tempList reference myList. Try this instead : dim tempList as new List (Of Something)(myList)


I think if you called myCalledFunction(byVal aListCopy as Something) you can let the framework do the work.


If your list consists of value types you can just create a new list with the old list passed in the constructor. If you are going to be doing a deep copy of a reference object your best bet is to have your reference type implement ICloneable (example). You can then loop through and clone each object or you could add an extension method (like this c# example).


Try this - use LINQ to create a new list from the original, for example:

Sub Main()
        Dim nums As New List(Of Integer)

        nums.Add(1)
        nums.Add(2)
        nums.Add(3)
        nums.Add(4)

        Dim k = (From i In nums _
                 Select i).ToList()

    For Each number As Integer In nums
        k.Remove(number)
    Next
    End Sub

k will then be a new list of numbers which are not linked to the source.

0

精彩评论

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