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

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

    Building on Marc's answer but adding the desired cloning behaviour

    public static T[] CloneSubArray(this T[] data, int index, int length)
        where T : ICloneable
    {
        T[] result = new T[length];
        for (int i = 0; i < length; i++)
        { 
            var original = data[index + i];
            if (original != null)
                result[i] = (T)original.Clone();            
        return result;
    }
    

    And if implementing ICloneable is too much like hard work a reflective one using Håvard Stranden’s Copyable library to do the heavy lifting required.

    using OX.Copyable;
    
    public static T[] DeepCopySubArray(
        this T[] data, int index, int length)
    {
        T[] result = new T[length];
        for (int i = 0; i < length; i++)
        { 
            var original = data[index + i];
            if (original != null)
                result[i] = (T)original.Copy();            
        return result;
    }
    

    Note that the OX.Copyable implementation works with any of:

    For the automated copy to work, though, one of the following statements must hold for instance:

    • Its type must have a parameterless constructor, or
    • It must be a Copyable, or
    • It must have an IInstanceProvider registered for its type.

    So this should cover almost any situation you have. If you are cloning objects where the sub graph contains things like db connections or file/stream handles you obviously have issues but that it true for any generalized deep copy.

    If you want to use some other deep copy approach instead this article lists several others so I would suggest not trying to write your own.

提交回复
热议问题