我有一个包含10个元素的数组X。我想创建一个新数组,包含X中从索引3开始并在索引7结束的所有元素。当然,我可以很容易地写一个循环,将它为我,但我想保持我的代码尽可能干净。c#中有一个方法可以帮我做这个吗?

类似(伪代码):

Array NewArray = oldArray.createNewArrayFromRange(int BeginIndex , int EndIndex)

数组中。拷贝不符合我的需要。我需要在新数组中的项目是克隆。数组中。copy只是一个c风格的memcpy等效,这不是我要找的。


当前回答

array1 = [5,6,7,8];

int[] array2 = new int[2];

Array.ConstrainedCopy(array1, 1, array2, 0, 2);

array2 = [6,7];

数组中。ConstrainedCopy有五个(5)参数:

源数组 源数组的起始索引(sourceIndex) 目标数组(destinationArray) 目标数组起始索引(destinationIndex) 要复制的元素数量(长度)

其他回答

我不确定它到底有多深,但是:

MyArray ToList < TSource >()。GetRange (beginningIndex, endIndex) . ToArray ()

这是一些开销,但它可能会减少一个不必要的方法。

那么使用数组呢?ConstrainedCopy:

int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
Array.ConstrainedCopy(ArrayOne, 3, ArrayTwo, 0, 7-3);

以下是我的原帖。这是行不通的

你可以使用数组。CopyTo:

int[] ArrayOne = new int[8] {1,2,3,4,5,6,7,8};
int[] ArrayTwo = new int[5];
ArrayOne.CopyTo(ArrayTwo,3); //starts copy at index=3 until it reaches end of
                             //either array

来自System.Private.CoreLib.dll的代码:

public static T[] GetSubArray<T>(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>();
        }
        T[] array2 = new T[item2];
        Buffer.Memmove(ref Unsafe.As<byte, T>(ref array2.GetRawSzArrayData()), ref Unsafe.Add(ref Unsafe.As<byte, T>(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;
}

array1 = [5,6,7,8];

int[] array2 = new int[2];

Array.ConstrainedCopy(array1, 1, array2, 0, 2);

array2 = [6,7];

数组中。ConstrainedCopy有五个(5)参数:

源数组 源数组的起始索引(sourceIndex) 目标数组(destinationArray) 目标数组起始索引(destinationIndex) 要复制的元素数量(长度)

就克隆而言,我认为序列化不会调用构造函数。如果你在ctor中做一些有趣的事情,这可能会破坏类不变量。

似乎更安全的方法是调用复制构造函数的虚拟克隆方法。

protected MyDerivedClass(MyDerivedClass myClass) 
{
  ...
}

public override MyBaseClass Clone()
{
  return new MyDerivedClass(this);
}