Difference between the System.Array.CopyTo() and System.Array.Clone()

前端 未结 13 2158
攒了一身酷
攒了一身酷 2020-12-02 06:50

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

13条回答
  •  误落风尘
    2020-12-02 07:29

    As stated in many other answers both methods perform shallow copies of the array. However there are differences and recommendations that have not been addressed yet and that are highlighted in the following lists.

    Characteristics of System.Array.Clone:

    • Tests, using .NET 4.0, show that it is slower than CopyTo probably because it uses Object.MemberwiseClone;
    • Requires casting the result to the appropriate type;
    • The resulting array has the same length as the source.

    Characteristics of System.Array.CopyTo:

    • Is faster than Clone when copying to array of same type;
    • It calls into Array.Copy inheriting is capabilities, being the most useful ones:
      • Can box value type elements into reference type elements, for example, copying an int[] array into an object[];
      • Can unbox reference type elements into value type elements, for example, copying a object[] array of boxed int into an int[];
      • Can perform widening conversions on value types, for example, copying a int[] into a long[].
      • Can downcast elements, for example, copying a Stream[] array into a MemoryStream[] (if any element in source array is not convertible to MemoryStream an exception is thrown).
    • Allows to copy the source to a target array that has a length greater than the source.

    Also note, these methods are made available to support ICloneable and ICollection, so if you are dealing with variables of array types you should not use Clone or CopyTo and instead use Array.Copy or Array.ConstrainedCopy. The constrained copy assures that if the copy operation cannot complete successful then the target array state is not corrupted.

提交回复
热议问题