Difference between the System.Array.CopyTo() and System.Array.Clone()
System.Array.CopyTo()
和System.Array.Clone()
之间有什么区别?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
Edit: Remove the wrong example.
One other difference not mentioned so far is that
Clone()
the destination array need not exist yet since a new one is created from scratch. CopyTo()
not only does the destination array need to already exist, it needs to be large enough to hold all the elements in the source array from the index you specify as the destination. Both perform shallow copies as @PatrickDesjardins said (despite the many misled souls who think that CopyTo
does a deep copy).
However, CopyTo
allows you to copy one array to a specified index in the destination array, giving it significantly more flexibility.
上一篇: 什么是复制列表的最佳方式?