获取多维数组的大小只给出了泛型类型 [英] Get multi-dimensional array sizes given only generic type

查看:86
本文介绍了获取多维数组的大小只给出了泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我尝试以accomplish-我找到可用的罗斯林的C#交互窗口是非常有用的。其中一个它更有趣的功能是它可以采取任何的IEnumerable 并打印其内容在人类可读的形式。

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.

例如,键入:

变种一个新= [,] {{3,4},{5,6}};一个

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

将会打印:

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

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

我试图复制在的IEnumerable 在我自己的扩展方法,这种行为(用于调试)。打印元素本身是容易的,我快到的问题是如何在给定仅数组维度的IEnumerable< T>

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();
}

我的问题是什么是得到多维数组在我的评论表明的尺寸最好的方法是什么?我没有看到键入这符合该法案。

推荐答案

既然你知道你正在使用的阵列通过您的的检查IsArray的,你可以投枚举阵列并获得数组边界如下

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;
}

其中,排名告诉你维数组中的号码,然后在随后对对GetLength 对于一个给定维会告诉你,特定尺寸的大小。

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.

这篇关于获取多维数组的大小只给出了泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆