【问题标题】:C# Elements in Dimension维度中的 C# 元素
【发布时间】:2017-04-03 22:16:35
【问题描述】:

我想使用 C# 找出提供的维度中的元素数量:

int [][] arr = new int [3][];
int elements_dim0 = arr.GetLength(0); // Returns 3, which is the size of dimension. I want it to return the actual count of elements in provided dimension.

【问题讨论】:

    标签: c# .net arrays multidimensional-array


    【解决方案1】:

    int [][] 不是多维数组 - 它的锯齿状数组(即它是数组数组)。如果你想在某个索引处获取数组的长度,你应该使用

    arr[0].Length
    

    但请确保在获取数组元素的长度之前已对其进行了初始化(否则您将得到 NullReferenceException)。例如:

    arr[0] = new int[] { 1, 2, 3 };
    arr[1] = new int[] { 4, 5 };
    

    您还可以使用数组初始化语法来初始化锯齿数组:

    int[][] arr = { new[] { 1, 2, 3 }, new[] { 4, 5 }, new[] { 6 } };
    

    请注意,多维数组定义为int [,]。您可以使用GetLowerBound(int dimension)(通常为零)和GetUpperBound(int dimension) 来获取每个数组维度的边界。例如。创建大小为 2 x 4 的多维数组:

    int[,] grid = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
    grid.GetUpperBound(0);  // 1
    grid.GetUpperBound(1);  // 3
    

    进一步阅读:Jagged ArraysMultidimensional Arrays

    【讨论】:

    • 谢谢,刚刚明白我的问题有多愚蠢)
    • @Src 没有愚蠢的问题:)
    猜你喜欢
    • 2021-12-30
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多