Programmatically Declare Array of Arbitrary Rank

后端 未结 3 567
走了就别回头了
走了就别回头了 2021-01-14 01:29

In C#, there are three types of arrays: one-dimensional, jagged, and multi-dimensional rectangular.

The question is: given an array of a specific size, how can we cr

3条回答
  •  旧巷少年郎
    2021-01-14 02:08

    You can populate an array of lengths (one per rank) based on the existing array, and then use Array.CreateInstance(Type, int[]). So:

    public static Array CreateNewArrayOfSameSize(Array input)
    {
        int[] lengths = new int[input.Rank];
        for (int i = 0; i < lengths.Length; i++)
        {
            lengths[i] = input.GetLength(i);
        }
        return Array.CreateInstance(array.GetType().GetElementType(), lengths);
    }
    

    It's a shame there isn't a method to return all the lengths in one go, but I can't see one. Also I'm surprised that there isn't an ElementType property on Array, but again it may just be eluding me.

    Note that this doesn't attempt to maintain the same upper/lower bounds for each dimension as the original array - just the sizes.

提交回复
热议问题