2

假设我有一个 n 维数的 .NET 数组。我想遍历元素并打印出如下内容:

[0, 0, 0] = 2
[0, 0, 1] = 32

等等。我可以使用一些 Rank 和 dimension 函数编写一个循环来得出索引。是否有内置功能?

4

2 回答 2

2

感谢您的回答,这是我在等待时写的:

public static string Format(Array array)
{
    var builder = new StringBuilder();
    builder.AppendLine("Count: " + array.Length);
    var counter = 0;

    var dimensions = new List<int>();
    for (int i = 0; i < array.Rank; i++)
    {
        dimensions.Add(array.GetUpperBound(i) + 1);
    }

    foreach (var current in array)
    {
        var index = "";
        var remainder = counter;
        foreach (var bound in dimensions)
        {
            index = remainder % bound + ", " + index;
            remainder = remainder / bound;
        }
        index = index.Substring(0, index.Length - 2);

        builder.AppendLine("   [" + index + "] " + current);
        counter++;
    }
    return builder.ToString();
}
于 2008-08-25T18:23:38.977 回答
1

看看这个:可能对你有帮助。

于 2008-08-25T18:11:57.303 回答