在java中,我可以这样做:
Square[][][] sheets;
public final Square[][] getSheet(int index) {
return sheets[index];
}
c#中的等价物是什么?由于多维数组的语法略有不同:
Square[,,] Sheets;
public Square[,] GetSheet(int index) {
return ????
}
答案 0 :(得分:6)
如果使用锯齿状的数组,C#中的等价物是相同的:
private Square[][][] sheets;
public Square[][] GetSheet(int index)
{
return sheets[index];
}
如果你有一个多维数组,那么获得这三个维度中的两个并不是一个简单的方法。您可以做的最好的事情是重新创建数组:
private Square[,,] sheets;
public Square[,] GetSheet(int index)
{
int x = sheets.GetLength(0);
int y = sheets.GetLength(1);
Square[,] sheet = new Square[x,y];
for(int i = 0; i < x; i++)
for(int j = 0; j < y; j++)
sheet[i,j] = sheets[i,z,index];
return sheet;
}
如何初始化
Square[4][4][4]
?
您可以循环并初始化每个维度:
for(int i = 0; i < 4; i++)
{
sheets[i] = new Square[4][];
for(int j = 0; j < 4; j++)
{
sheets[i][j] = new Square[4];
}
}
(请注意,如果Square
是引用类型,那么 还需要将每个Square[i][j][k]
初始化为一个值,否则它将是null
)
或使用数组初始化语法;
sheets = new Square[4][][]
{
new Square[4][] {new Square[4], new Square[4], new Square[4], new Square[4],},
new Square[4][] {new Square[4], new Square[4], new Square[4], new Square[4],},
new Square[4][] {new Square[4], new Square[4], new Square[4], new Square[4],},
new Square[4][] {new Square[4], new Square[4], new Square[4], new Square[4],},
};
显然,循环比初始化语法更容易扩展。