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

前端 未结 25 1409
北海茫月
北海茫月 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:45

    How about this:

    public T[] CloneCopy(T[] array, int startIndex, int endIndex) where T : ICloneable
    {
        T[] retArray = new T[endIndex - startIndex];
        for (int i = startIndex; i < endIndex; i++)
        {
            array[i - startIndex] = array[i].Clone();
        }
        return retArray;
    
    }
    

    You then need to implement the ICloneable interface on all of the classes you need to use this on but that should do it.

提交回复
热议问题