如何将一系列数组元素克隆到新数组

如何将一系列数组元素克隆到新数组

本文介绍了如何将一系列数组元素克隆到新数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有10个元素的数组X.我想创建一个新数组,其中包含X中所有从索引3开始到索引7结束的元素.当然,我可以轻松编写一个循环来为我做一个循环,但是我想保持代码尽可能整洁. C#中有什么方法可以帮我吗?

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 loop that will do it for me but I would like to keep my code as clean as possible. Is there a method in C# that can do it for me?

类似(伪代码)的

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

Array.Copy不符合我的需求.我需要新阵列中的项目才能克隆. Array.copy只是C风格的memcpy等效项,不是我想要的.

Array.Copy doesn't fit my needs. I need the items in the new array to be clones. Array.copy is just a C-Style memcpy equivalent, it's not what I'm looking for.

推荐答案

您可以将其添加为扩展方法:

You could add it as an extension method:

public static T[] SubArray<T>(this T[] data, int index, int length)
{
    T[] result = new T[length];
    Array.Copy(data, index, result, 0, length);
    return result;
}
static void Main()
{
    int[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int[] sub = data.SubArray(3, 4); // contains {3,4,5,6}
}


更新重新克隆(在原始问题中并不明显).如果您真的想要深入的克隆,请;像这样:


Update re cloning (which wasn't obvious in the original question). If you really want a deep clone; something like:

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
    T[] arrCopy = new T[length];
    Array.Copy(data, index, arrCopy, 0, length);
    using (MemoryStream ms = new MemoryStream())
    {
        var bf = new BinaryFormatter();
        bf.Serialize(ms, arrCopy);
        ms.Position = 0;
        return (T[])bf.Deserialize(ms);
    }
}

这确实要求对象可序列化([Serializable]ISerializable).您可以根据需要轻松替换任何其他串行器-XmlSerializerDataContractSerializer,protobuf-net等.

This does require the objects to be serializable ([Serializable] or ISerializable), though. You could easily substitute for any other serializer as appropriate - XmlSerializer, DataContractSerializer, protobuf-net, etc.

请注意,如果不进行序列化,则深度克隆很棘手.特别是ICloneable在大多数情况下很难让人信服.

Note that deep clone is tricky without serialization; in particular, ICloneable is hard to trust in most cases.

这篇关于如何将一系列数组元素克隆到新数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:37