如何在数组中移动按钮并设置null的来源

本文关键字:null 设置 按钮 数组 移动 | 更新日期: 2023-09-27 18:13:13

我有MyButtons的多维数组originalArray[X_VECTOR, Y_VECTOR]

MyButton是一个简单的创建类(可能没有必要):

class MyButton : Button
{
    private int[] id;
    public MyButton()
    {
        id = new int[2];
    }
    public int[] ID
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }
}

在循环中填充按钮数组:

public void fillArray() {
    originalArray = new MyButton[X_VECTOR, Y_VECTOR];
    int count_buttons = 0;
    for (int i = 0; i < X_VECTOR; ++i)
    {
        for (int j = 0; j < Y_VECTOR; ++j)
        {
            count_buttons++;
            MyButton btn = new MyButton();
            btn.Name = "btn " + count_buttons;
            btn.ID[0] = i;
            btn.ID[1] = j;
            originalArray[i, j] = btn;   
        }
     }
}

现在,我们想要在数组中move button to right side after click:

protected void MyBtnClick(object sender, EventArgs e) {
    if (sender != null) {
        MyButton myclickbutton = (MyButton)sender;
        int x = myclickbutton.ID[0];
        int y = myclickbutton.ID[1];
        MyButton temp = originalArray[x, y];
        temp.Location = new Point(curr_pos_x + 55, curr_pos_y);
        temp.ID[0] = x; 
        temp.ID[1] = y + 1; // new coordinate y
        originalArray[x, y + 1] = temp;
        temp = null;
        // originalArray[x, y] = null;
    }
}

NULL不被设置。我哪里出错了?

我需要这张插图:

BEFORE CLICK:

originalArray[0,0] = btn instance; 
originalArray[0,1] = null;

AFTER CLICK:

originalArray[0,0] = null; 
originalArray[0,1] = btn instance;
编辑:

当我尝试这个时:

protected void MyBtnClick(object sender, EventArgs e) {
    if (sender != null) {
        MyButton myclickbutton = (MyButton)sender;
        int x = myclickbutton.ID[0];
        int y = myclickbutton.ID[1];
        myclickbutton.Location = new Point(curr_pos_x + 55, curr_pos_y);
        myclickbutton.ID[0] = x;
        myclickbutton.ID[1] = y + 1;
        originalArray[x, y + 1] = myclickbutton;
        originalArray[x, y] = null;
    }
}

也许可以,但是当我测试这个

if ((originalArray[i, j].Name == testArray[i, j].Name)) ...

这一行让我得到NullReferenceException

这个函数与上面的fillArray相同,我在构造函数中调用它:

public void createTestArray() {
        testArray = new MyButton[X_VECTOR, Y_VECTOR];
        int count_buttons = 0;
        for (int i = 0; i < X_VECTOR; ++i)
        {
            for (int j = 0; j < Y_VECTOR; ++j)
            {
                count_buttons++;
                MyButton btn = new MyButton();
                btn.Name = "btn " + count_buttons;
                testArray[i, j] = btn;   
            }
         }
}

如何在数组中移动按钮并设置null的来源

您将数组中的一个项设置为空,现在您遍历所有项,空项会抛出异常。只需要在比较名称之前检查item是否为空,就不会出现异常

您收到一条消息说Null is not set。您已经注释掉了将多维数组中的原始xy条目返回为空的行。你现在得到的是:

originalArray[0,0] = btn instance; 
originalArray[0,1] = temp;

删除最后一行的注释,并在0,0中删除btn instance