【发布时间】:2020-06-14 01:10:17
【问题描述】:
我正在制作一个记忆游戏,将两张牌与自己进行比较,看看它们是否相同。我通过比较图片框中图像的标签来做到这一点。所有图像都有唯一的标签,但是,当在 if 语句中进行比较时,它会忽略并将其视为 false。这是点击卡片时的代码。
private void pictureBox1_Click(object sender, EventArgs e)
{
Image temp = Boxes[0];
pictureBox1.Tag = Boxes[0].Tag;
pictureBox1.Image = temp;
if (openBox1 == null)
{
openBox1 = pictureBox1;
}
else if (openBox1 != null && openBox2 == null)
{
openBox2 = pictureBox1;
}
if (openBox1 != null && openBox2 != null)
{
if (openBox1.Image.Tag == openBox2.Image.Tag)
{
openBox1 = null;
openBox2 = null;
}
else
{
openBox1.Image = Properties.Resources.card;
openBox2.Image = Properties.Resources.card;
openBox1 = null;
openBox2 = null;
}
}
}
这就是我标记图像的方式:
List<int> Repeats = new List<int>();
int random;
bool test;
foreach (Image n in Album)//checks to see if image has been added
{
test = true;
while (test)
{
random = randy.Next(0, 16);
if (!Repeats.Contains(random))
{
Boxes[random] = n;
Boxes[random].Tag = n.Width * n.Height;
Repeats.Add(random);
test = false;
}
}
}
我已亲自进入该程序,并监控变量。当我点击两张同一张卡片时,它只是忽略了它们是相同的值。
【问题讨论】:
-
Tag的类型为object。当你写if (...Tag == ...Tag)时,你比较的是references,而不是values。 -
@AlexanderPetrov 那么我是否首先必须将标签值转换为 int 才能正常工作?或者说这种方式是不可能的。
-
是的,将
Tag转换/转换为int。
标签: c# winforms picturebox