1

很难理解类以及为什么我无法访问某些对象。如何修改代码以便可以更改所有类/事件中的“地图”(这是一堆标签)属性?

Draw2d() 方法在主窗体上创建了几个标签,我希望在不同的事件上更改它们(在此示例中单击按钮)。

有人可以帮助我,或者只是提示我正确的方向。

编码:

公共部分类Form1:表格

{  
    public void Draw2d()  
    {  
        const int spacing = 20;  
        Label[][] map = new Label[5][];  
        for (int x = 0; x < 5; x++) 
        {  
            map[x] = new Label[5];  
            for (int y = 0; y < 5; y++)  
            {  
                map[x][y] = new Label();  
                map[x][y].AutoSize = true;  
                map[x][y].Location = new System.Drawing.Point(x * spacing, y * spacing);  
                map[x][y].Name = "map" + x.ToString() + "," + y.ToString();  
                map[x][y].Size = new System.Drawing.Size(spacing, spacing);  
                map[x][y].TabIndex = 0;  
                map[x][y].Text = "0";  
            }  
            this.Controls.AddRange(map[x]);  
        }  
    }  

    public Form1()  
    {
        InitializeComponent();  
    }  

    public void Form1_Load(object sender, EventArgs e)  
    {  
        Draw2d();  
    }

    private void button1_Click(object sender, EventArgs e)
    {  
        map[0][0].Text = "1";               //        <-- Doesn't work
    }


}

谢谢!

4

2 回答 2

2

您必须将地图声明为属性(全局到类)

public partial class Form1 : Form {
   public Label[][] map;
   ....
}

然后你可以在类内使用

this->map[...][...]

或从外面喜欢

objClass->map[...][...]
于 2010-01-23T22:57:39.727 回答
1

我的猜测是你添加了

public Label[][] map;

但忘记将 Draw2d 的第二行从

Label[][] map = new Label[5][];

map = new Label[5][];

我刚刚尝试了您的代码,如果您更改这两行,它就可以正常工作。如果这不是问题,请您说一下您遇到了什么错误?

于 2010-01-23T23:20:14.260 回答