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

本文关键字:查找 多少 Array System 何计算 计算 | 更新日期: 2023-09-27 18:31:20

如果我有一个未知数组作为 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;
    }

谢谢。

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

您要查找的关键字是排名。使用 Rank 属性找出数组有多少维。

你在找Array.Rank吗?

该属性将返回数组中的维数。对于单维数组等,将返回值 1。

然后,可以调用 Array.GetLength() 来确定每个维度的长度。

如果你有一个接受任何维度数组的函数,并且你需要在强制转换它之前知道它有多少维,你可以使用:

array.GetType().GetArrayRank()

你应该能够使用 Rank。 Array.Rank具体来说。 下面是它的 MSDN 信息:http://msdn.microsoft.com/en-us/library/system.array.rank(v=vs.110).aspx