C# 如何在C中将ArrayObject值初始化为零#

C# 如何在C中将ArrayObject值初始化为零#,c#,arrays,multidimensional-array,C#,Arrays,Multidimensional Array,我有 单元[,]单元=新单元[6,6]; 我想将所有值初始化为零 我做了这样的事 对于(int i=1;i你可以这样说: 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; } } 类单

我有

单元[,]单元=新单元[6,6];
我想将所有值初始化为零
我做了这样的事

对于(int i=1;i你可以这样说:

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;
  }
}
类单元{
公共整数x{get;set;}
公共整数y{get;set;}
战士{get;set;}
};
细胞[,]细胞=新细胞[6,6];
//数组在C#中是以零为基的,因此它们以0开头
对于(int i=0;i
按照您的类先将
x
y
公开(假设您使用的是非
单元格中的方法访问它们:

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
    }; 
然后您应该可以访问您的班级成员:

class Cell
{
    public int x;
    public int y; 
    Warrior warrior;
};
细胞[,]细胞=新细胞[6,6]

Cell(Warrior getWarrior)
{ 
    x = 0; 
    y = 0; 
    warrior = getWarrior;
} 
for(int i=0;i<6;i++)
{
对于(int j=0;j<6;j++)
{
单元[i,j]=新单元(sendWarrior);
WriteLine(“\t{0}{1}”,单元格[i,j].x,单元格[i,j].y);
}
}

什么是
单元格
?它是结构还是类?而且
单元格[,]单元格=新单元格[6,6];
不会编译什么是单元格?你创建了一个类吗?什么是
单元格
?它能容纳
int
值或
字符串
?它是类单元格{int x,int y,Warrior Warrior};@PushpitaShrestha-您是否尝试过
单元格[i,j].x=0;
单元格[i,j].y=0;
?我不确定这段代码是否比OP已经发布的代码更好。我尝试过打印控制台。写入(“\t{0}”,单元格[i,j])但它会引发未处理的异常。未处理的异常:System.NullReferenceException:Object reference未设置为对象的实例。@PushpitaShrestha-它会引发该异常-以这种方式打印-
Console.Write(“\t{0}”,单元格[i,j].x)
Cell(Warrior getWarrior)
{ 
    x = 0; 
    y = 0; 
    warrior = getWarrior;
} 
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);
    }
}