Get multi-dimensional array sizes given only gener

2019-08-11 21:25发布

First, what I'm trying to accomplish- I find the C# interactive window available with Roslyn to be very useful. One of it's more interesting features is that it can take any IEnumerable and prints out its contents in a human readable form.

For example, typing:

var a = new[,] { {3, 4}, {5, 6} }; a

Will print:

int[2, 2] { { 3, 4 }, { 5, 6 } }

I'm trying to replicate this behavior in my own extension method on IEnumerable (for debugging purposes). Printing the elements themselves is easy, the trouble I'm running into is how to get the array dimensions given only an IEnumerable<T>.

This is what I have so far for getting the type's name and size:

private static String getFormattedTypeName<T>(IEnumerable<T> enumerable)
{            
    var enumerableType = enumerable.GetType();

    var typeNameAndSize = new StringBuilder();
    typeNameAndSize.Append(enumerableType.Name.Split('`').First());

    var genericArguments = enumerableType.GetGenericArguments();
    if (genericArguments.Length != 0)
    {
        typeNameAndSize.Append(String.Format("<{0}> ({1})", 
            String.Join(",", genericArguments.Select(t => t.Name)),
            enumerable.Count()));
    }
    else if (enumerableType.IsArray)
    {
        //Can I get the length of each array dimension from the type???
    }

    return typeNameAndSize.ToString();
}

My question is what is the best way to get the dimensions of multi-dimensional arrays where my comment indicates? I don't see any methods on Type which fit the bill.

1条回答
再贱就再见
2楼-- · 2019-08-11 22:09

Given that you know you are working with an Array via your check of IsArray, you can cast the enumerable to an Array and get the array bounds as follows:

private static Int32[] GetArrayBounds(Array value)
{
    var bounds = new Int32[value.Rank];
    for (var i = 0; i < value.Rank; i++)
        bounds[i] = value.GetLength(i);

    return bounds;
}

Where Rank tells you the number of dimensions in the array, and then subsequent calls to GetLength for a given dimension will tell you the size of that particular dimension.

查看更多
登录 后发表回答