How do I clone a range of array elements to a new array?

前端 未结 25 1405
北海茫月
北海茫月 2020-11-22 16:07

I have an array X of 10 elements. I would like to create a new array containing all the elements from X that begin at index 3 and ends in index 7. Sure I can easily write a

25条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 16:48

    Cloning elements in an array is not something that can be done in a universal way. Do you want deep cloning or a simple copy of all members?

    Let's go for the "best effort" approach: cloning objects using the ICloneable interface or binary serialization:

    public static class ArrayExtensions
    {
      public static T[] SubArray(this T[] array, int index, int length)
      {
        T[] result = new T[length];
    
        for (int i=index;i

    This is not a perfect solution, because there simply is none that will work for any type of object.

提交回复
热议问题