2010-10-18 45 views
1

这可能是一个范围界定问题,但下面的代码死亡。我从2个类Cell和Map构建了一个多维数组。该地图是一个由X大小的单元格组成的网格。目前为止很正常(当我学习一种新语言时,我不断重写这个程序)。为了简洁起见,我只会发布类和反映错误的基本测试。当我去打印,当我去打印整个网格阵列我的construtor期间initalized消失在地图(空异常,因为电网结束了空一些如何......)学习与阵列(阵列数据消失)C#问题

//misc using up here 

namespace Mapper { 
class Program { 

static void Main(string[] args) 
{ //TODO Parser 

int max_x=2; 
int max_y=2; 

Map myMap = new Map(max_x,max_y); 
myMap.print(); 


} 

class Cell 
{ 
public char type='o'; 
public Cell(char inittype){ 
this.type=inittype; 
} 

public void printCell(){ 
Console.Write(this.type); } 

public void set(char value){ 
this.type = value; } 
} 

class Map 
{ 
private int max_X; //global 
private int max_Y; //global 
public Cell[,] grid; //global 

public Map(int maxX, int maxY) { 
Cell[,] grid = new Cell[maxX, MaxY]; 
this.max_X = maxX; //Store constructor provided dimensions for global use 
this.max_Y = maxY; 
for(int yv=0; yv &lt max_Y; yv++){ 
    for(int xv=0, xv &lt max_X;xv++){ 
    grid[xv,yx] = new Cell('x'); 
    } 
} 

public void print() { 
for(int yv=0; yv &lt max_Y; yv++){ 
    for(int xv=0, xv &lt max_X;xv++){ 
    grid[xv,yx].printCell(); 
    } 
} 

}} 

运行跟踪一切看起来都很正常,直到Map myMap行完成...换句话说,它看起来像构造函数不“粘”,我最终得到一个空的网格(它们都是空的)。我只能假设它是一个范围问题。 ..我错过了什么....?我是否构造了构造函数?

回答

8

的问题是在这里:

public Cell[,] grid; //global 

public Map(int maxX, int maxY) { 
    Cell[,] grid = new Cell[maxX, MaxY]; 
    ... 

您已经声明称为电网称为网格中的局部变量的实例成员,但你只更新本地变量。

要修复它,改变上述这最后一行:

grid = new Cell[maxX, maxY]; 

也有大量的代码编译错误的 - 在问题的代码不可能是你的代码运行。下次请使用复制并粘贴将代码复制到问题中。

此外,评论//global是误导。实例成员不是全局变量。与C#中的全局变量最接近的是静态成员。

+0

全球性的参考文献是“全球范围内的知名度”,而不是整个计划。 – Idgarad 2010-10-20 18:34:54

0

在您的构造函数中,您将分配给本地网格变量,而不是类网格变量。

Cell[,] grid = new Cell[maxX, MaxY]; 

应该

this.grid = new Cell[maxX, maxY]; 
+0

这就像一个冠军!谢谢。 – Idgarad 2010-10-20 15:16:55

0

在构造函数中,你声明细胞[,]格,这是隐藏的类级单元[,]网格。 :)