c# - 如何初始化二维数组中的对象?

标签 c# multidimensional-array

我得到了一个二维数组

BoardTile tiles[,];

然后在 Init(Point size) 中设置它的大小:

tiles = new BoardTile[size.X, size.Y];

以及如何初始化所有这些元素,因为它不使用默认的 BoardTile() 构造函数。它只是分配 null

foreach(BoardTile t in tiles) t = new BoardTile()

不起作用。当我尝试打电话时

foreach(BoardTile t in tiles) t.anything()

我得到 NullReferenceException

最佳答案

您可以尝试嵌套循环:

  for (int i = 0; i < titles.GetLength(0); ++i)
    for (int j = 0; j < titles.GetLength(1); ++j)
      titles[i, j] = new BoardTile();

编辑:如果嵌套循环太复杂且不可读,请尝试切换到锯齿状数组,即数组的数组 - BoardTile tiles [][]; - 来自 2D 一个 BoardTile tiles[,],例如

   // created and initialized jagged array
   BoardTile tiles[][] = Enumerable
     .Range(size.Y)                      // size.Y lines
     .Select(y => Enumerable             // each line is
        .Range(size.X)                   //   size.X items
        .Select(x => new BoardTile())    //   each of them is BoardTile()
        .ToArray())                      //   materialized as array
     .ToArray();                         // all arrays are array of array 

关于c# - 如何初始化二维数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55140666/

相关文章:

python - 连接 Numpy 数组而不复制

c# - ASP.Net Core 3.1 MVC - 带有对象列表的多选

c# - "Indicates the start of a managed heap garbage collection"到底是什么意思,是不是不好?

matlab - 你能在 MATLAB 中像集合一样定义变量吗?

java 。为什么这个for循环不能正常工作

java - 在 Java 中将 2d 数组转换为列表列表

c# - 获取非 GDI 应用程序中的插入符位置

c# - 将多个文件传递给函数

c# - Entity Framework EdmFunction 导入无法识别

java - 数组 : Find array[x][1] for different x