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

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

    Code from the System.Private.CoreLib.dll:

    public static T[] GetSubArray(T[] array, Range range)
    {
        if (array == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
        }
        (int Offset, int Length) offsetAndLength = range.GetOffsetAndLength(array.Length);
        int item = offsetAndLength.Offset;
        int item2 = offsetAndLength.Length;
        if (default(T) != null || typeof(T[]) == array.GetType())
        {
            if (item2 == 0)
            {
                return Array.Empty();
            }
            T[] array2 = new T[item2];
            Buffer.Memmove(ref Unsafe.As(ref array2.GetRawSzArrayData()), ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), item), (uint)item2);
            return array2;
        }
        T[] array3 = (T[])Array.CreateInstance(array.GetType().GetElementType(), item2);
        Array.Copy(array, item, array3, 0, item2);
        return array3;
    }
    


提交回复
热议问题