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

类似(伪代码):

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

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


当前回答

数组中。ConstrainedCopy将工作。

public static void ConstrainedCopy (
    Array sourceArray,
    int sourceIndex,
    Array destinationArray,
    int destinationIndex,
    int length
)

其他回答

我认为你要找的代码是:

阵列。复制(oldArray, 0, newArray,开始,EndIndex -开始)

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 ()

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

克隆数组中的元素并不是一种通用的方法。您想要深度克隆还是所有成员的简单副本?

让我们采用“尽最大努力”的方法:使用ICloneable接口或二进制序列化克隆对象:

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

    for (int i=index;i<length+index && i<array.Length;i++)
    {
       if (array[i] is ICloneable)
          result[i-index] = (T) ((ICloneable)array[i]).Clone();
       else
          result[i-index] = (T) CloneObject(array[i]);
    }

    return result;
  }

  private static object CloneObject(object obj)
  {
    BinaryFormatter formatter = new BinaryFormatter();

    using (MemoryStream stream = new MemoryStream())
    {
      formatter.Serialize(stream, obj);

      stream.Seek(0,SeekOrigin.Begin);

      return formatter.Deserialize(stream);
    }
  }
}

这并不是一个完美的解决方案,因为没有一个解决方案适用于任何类型的对象。

它不符合你的克隆要求,但它似乎比许多答案要简单:

Array NewArray = new ArraySegment(oldArray,BeginIndex , int Count).ToArray();