代码之家  ›  专栏  ›  技术社区  ›  IAbstract

为什么“new int[x]{}”无效?

  •  1
  • IAbstract  · 技术社区  · 16 年前

    在MonoDevelop中,我编写了以下代码:

    int[] row = new int[indices.Count]{};
    

    但是,在运行时,我得到:

    我知道这个错误的含义,并强制我调整数组的大小:

    int[] row = new int[indices.Count]{};
    Array.Resize(ref row, rowWidth);
    

    4 回复  |  直到 16 年前
        1
  •  13
  •   LBushkin    16 年前

    不能将数组创建语法与对象初始化语法混合使用。拆下 { } .

    int[] row = new int[indices.Count];
    

    indices.Count 已初始化为默认值。

    int[] row = new int[] { 1, 2, 3, 4 };
    

    您正在创建一个数组,然后将其内容初始化为值[1,2,3,4]。数组的大小是根据元素的数量推断出来的。它是以下的简写:

    int[] row = new int[4];
    row[0] = 1;
    row[1] = 2;
    row[2] = 3;
    row[3] = 4;
    

    数组仍首先初始化为默认值 ,此语法只是提供了一个速记,以避免不得不自己编写这些额外的作业。

        2
  •  1
  •   Matthew Scharley    16 年前

    以下代码在Windows/.NET/LINQPad上由于同样的原因未能编译:

    void Main()
    {
        int[] row = new int[indices.Count]{};
        row[2] = 10;
        row.Dump();
    }
    
    // Define other methods and classes here
    public class indices {
        public static int Count = 5;
    }
    

    但是,从声明中删除对象初始化( {} )让它工作。

        3
  •  1
  •   Falle1234    16 年前

    在C#中,如果要声明空数组,语法应为:

    int[]行=新int[index.Count];

        4
  •  0
  •   Igor Zevaka    16 年前

    因为在使用数组初始化语法时,需要指定数组的大小

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

    int[] arr = new int[5];
    

    或使用初始化列表:

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