Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a typed array MyType[] types; and i want to make and independant copy of this array. i tried this

MyType[] types2 = new MyType[types.Length] ;

types2 = types ;

but this create a reference to the first. I then tried

Array.Copy( types , types2 , types.Length ) ;

but I have the same problem: changing a value in the first array changes the value in the copy as well.

How can I make a completely independent or deep copy of an Array, IList or IEnumerable?

See Question&Answers more detail:os

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

1 Answer

Based on the first post, all he needs is this for "an independent copy of the array". Changes to the shallowCopy array itself would not appear in the types array (meaning element assignment, which really is what he showed above despite saying "deep copy"). If this suits your needs, it will have the best performance.

MyType[] shallowCopy = (MyType[])types.Clone();

He also mentions a "deep copy" which would be different for mutable types that are not recursive value-type aggregates of primitives. If the MyType implements ICloneable, this works great for a deep copy:

MyType[] deepCopy = (MyType[])Array.ConvertAll(element => (MyType)element.Clone());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...