我有一个多维数组originalArray[X_VECTOR, Y_VECTOR]
。MyButtons
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;
}
}
}