我正在用C#进行内存匹配游戏 当用户匹配2张图像时,我希望它们消失或使其不可见 我仍然是编码的新手,这是我到目前为止所做的,但是图像不会不可见
private void apple1_Click(object sender, EventArgs e)
{
apple1.Image = Properties.Resources.apple;
bool condition = true;
if (apple1.Image==apple2.Image)
{
apple1.Visible = false;
apple2.Visible = false;
}
}
private void apple2_Click(object sender, EventArgs e)
{
apple2.Image = Properties.Resources.apple;
}
答案 0 :(得分:0)
设置apple1.Image = Properties.Resources.apple;
时,请注意,将Properties.Resources.apple
的值(图像)的副本设置为apple1.Image
时,分配给apple2.Image
时也会发生同样的情况,因此,尽管在视觉上它们似乎具有相同的图像,但是它们指向的是不同的图像(在内存中)。
您可以执行以下一项操作:
1-将图像设置为字典,然后从中加载apple1.Image
和apple2.Image
:
Dictionary<string, Image> Images = new Dictionary<string, Image>();
Images.Add("apple", Properties.Resources.apple);
Image apple = Properties.Resources.apple;
private void apple1_Click(object sender, EventArgs e)
{
apple1.Image = Images["apple"];
if (apple1.Image==apple2.Image)
{
apple1.Visible = false;
apple2.Visible = false;
}
}
private void apple2_Click(object sender, EventArgs e)
{
apple2.Image = Images["apple"];
}
2-只需使用另一个属性比较相等性即可:
private void apple1_Click(object sender, EventArgs e)
{
apple1.Image = Properties.Resources.apple;
apple1.Tag = "apple";
if ((string)apple1.Tag==(string)apple2.Tag)
{
apple1.Visible = false;
apple2.Visible = false;
}
}
private void apple2_Click(object sender, EventArgs e)
{
apple2.Image = Properties.Resources.apple;
apple2.Tag = "apple";
}
答案 1 :(得分:0)
正如其他人所说,您只需要存储所有资源一次。这是一个可能的示例:
class MyForm
{
private Dictionary<String, Image> images = new Dictionary<String, Image>();
public void Init()
{
images["apple"] = Properties.Resources.apple;
}
public void Dispose()
{
foreach(var item in myDictionary.Values)
{
item.Dispose();
}
}
private void apple1_Click(object sender, EventArgs e)
{
apple1.Image = images["apple"];
bool condition = true;
if (apple1.Image==apple2.Image)
{
apple1.Visible = false;
apple2.Visible = false;
}
}
private void apple2_Click(object sender, EventArgs e)
{
apple2.Image = images["apple"];
}
}