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

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

    You could add it as an extension method:

    public static T[] SubArray(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(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);
        }
    }
    

    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.

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

提交回复
热议问题