Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c# - Cloning List<T>

I thought that to clone a List you would just call:

List<int> cloneList = new List<int>(originalList);

But I tried that in my code and I seem to be getting effects that imply the above is simply doing:

cloneList = originalList... because changes to cloneList seem to be affecting originalList.

So what is the way to clone a List?

EDIT:

I am thinking of doing something like this:

public static List<T> Clone<T>(this List<T> originalList) where T : ICloneable
{
    return originalList.ConvertAll(x => (T) x.Clone());
}

EDIT2:

I took the deep copy code suggested by Binoj Antony and created this extension method:

public static T DeepCopy<T>(this T original) where T : class
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, original);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return (T)binaryFormatter.Deserialize(memoryStream);
    }
}

EDIT3:

Now, say the items in the List are structs. What then would result if I called?:

List<StructType> cloneList = new List<StructType>(originalList);

I am pretty sure than I would get a List filled with new unique items, correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This would work...

List<Foo> cloneList = new List<Foo>(originalList);

When you say "because changes to cloneList seem to be affecting originalList." - do you mean changes to the list, or changes to the items...

Adding / removing / swapping items is changing the list - so if we do:

cloneList.Add(anotherItem);

you should find that cloneList is longer than originalList. However, if the contents are reference-types (classes), then both lists are still pointing at the same underlying objects - so if we do:

cloneList[0].SomeObjectProperty = 12345;

then this will also show against originalList[0].SomeObjectProperty - there is only a single object (shared between both lists).

If this is the problem, you will have to clone the objects in the list - and then you get into the whole deep vs shallow issue... is this the problem?

For a shallow copy, you might be able to use something very much like the answer here - simply with TTo = TFrom (perhaps simplify to a single T).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...