如何在C#中将Array Object值初始化为ZERO

时间:2014-03-18 06:32:08

标签: c# arrays multidimensional-array

我有

Cell[,] cells = new Cells[6,6];
I want to initialize it all values to zero
I did something like this
for(int i=1; i<=6;i++) {
  for(int j=1; j<=6; j++) {
    cells[i,j] = 0;
  }
}

问题是它无法将int 0转换为Cell类型。如何首次将它们初始化为?例如:我有[6,6]数组,我想分配每个Cell [2,3] .Value = 0

由于

2 个答案:

答案 0 :(得分:0)

你可以这样说:

class Cell {
  public int x {get; set;}
  public int y {get; set;} 
  Warrior warrior {get; set;} 
};

Cell[,] cells = new Cells[6, 6];

// Arrays are zero-based in C#, so they start with 0
for(int i = 0; i < Cells.GetLength(0); i++) // <- Better get length than put "6"
  for(int j = 0; j < Cells.GetLength(1); j++) 
    cells[i, j] = new Cell() { // <- Do not forget to create Cell
      x = 0, // <- Overshoot, x will be 0 by default, to show the trick only
      y = 0  // <- Overshoot, y will be 0 by default, to show the trick only
    }; 

答案 1 :(得分:0)

  

问题是它无法将int 0转换为Cell类型。如何在第一次将它们初始化为零?

通过您的班级首先公开xy(假设您使用的方法不在Cell班级中访问它们:

class Cell
{
    public int x;
    public int y; 
    Warrior warrior;
};

然后你应该可以访问你的班级成员:

Cell[,] cells = new Cells[6,6];

for(int i=0; i<6;i++) 
{
    for(int j=0; j<6; j++) 
    {
        cells[i,j].x = cells[i,j].y = 0;
    }
}

以上是将值重置为0。如果你想在初始化时使用它,那么创建一个构造函数:

Cell(Warrior getWarrior)
{ 
    x = 0; 
    y = 0; 
    warrior = getWarrior;
} 

细胞[,]细胞=新细胞[6,6];

for (int i = 0; i < 6; i++)
{
    for (int j = 0; j < 6; j++)
    {
        cells[i, j]= new Cells(sendWarrior);
        Console.WriteLine("\t{0} {1}", cells[i, j].x, cells[i, j].y);
    }
}