C# System.Array 如何计算或查找它有多少维度?

标签 c# arrays multidimensional-array dimensions

如果我有一个未知数组作为 System.Array,我如何才能找到它有多少维度?我在想一些可以称为 Array.GetDimensionCount() 的东西

例如,如果我在 System.Array 类上构建扩展方法并且我想验证 arrayDimensionIndex 不大于或等于数组的维数,我想抛出 ArgumentOutOfRangeException

    /// <summary>
    /// Determines whether the value of the specified arrayIndex is within 
    /// the bounds of this instance for the specified dimension.
    /// </summary>
    /// <param name="instance">The instance of the array to check.</param>
    /// <param name="arrayDimensionIndex">Index of the array dimension.</param>
    /// <param name="arrayIndex">The arrayIndex.</param>
    /// <returns></returns>
    /// <exception cref="System.ArgumentOutOfRangeException">
    /// If arrayDimensionIndex exceeds the number of dimesnions in the array.
    /// </exception>
    public static bool IsInBounds(this Array instance, int arrayDimensionIndex, int arrayIndex)
    {
        // Determine if this instance has more dimension than the specified array dimension to check.
        if(instance.Get?????() <= arrayDimensionIndex)
        {
            throw new ArgumentOutOfRangeException();
        }

        // Get the length of the dimension specifed
        int arraDimensionLength = instance.GetLength(arrayDimensionIndex);

        // Check if the value is withing the array bounds
        bool isInBounds = ((uint)arrayIndex < arraDimensionLength);

        // Return the result
        return isInBounds;
    }

谢谢。

最佳答案

您要查找的关键词是Rank .使用 Rank 属性找出数组的维数。

关于C# System.Array 如何计算或查找它有多少维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27033641/

相关文章:

c# - 在 ConverterParameter 中使用反斜杠

c# - 编辑javascript文件后需要构建吗?

c# - 相当于 C 的 fread 文件 i/o 的 C#

php - 写入多维数组的位置

objective-c - 如何访问对象数组的元素

c# - 通过 ref - 内存占用在堆栈上传递 'value type'

c - 奇怪的数组初始化表达式?

arrays - 在多维数组上一起使用 `flatMap().filter().map()`

java - 如何使用Java中的Scanner创建具有指定行大小的二维数组而不指定列大小?

c++ - 访问保存在 unique_ptr 的多维 vector 中的对象的方法