简体   繁体   English

图片框的Image.Tag在if语句中不起作用

[英]Image.Tag of picture Box not working in if statement

I am making a memory game that compares two cards against themselves to see if they are the same.我正在制作一个 memory 游戏,将两张牌与自己进行比较,看看它们是否相同。 I do this by comparing the tag of the image in the picture box.我通过比较图片框中图像的标签来做到这一点。 All of the images have unique tags, however, when compared in an if statement, it passes over and treats it as false.所有图像都有唯一的标签,但是,当在 if 语句中进行比较时,它会忽略并将其视为 false。 This is the code for when the card is clicked on.这是点击卡片时的代码。

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;
            }
        }
    }

This is how I am tagging the images:这就是我标记图像的方式:

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;
                }
            }

        }

I have stepped into the program for myself, and monitored the variables.我已经为自己踏入了该计划,并监控了变量。 When I click two of the same card it just ignores that they are the same value.当我点击两张同一张卡片时,它只是忽略了它们是相同的值。

The code doesn't works because boxing.该代码不起作用,因为拳击。 int is a value type, to cast it to object (the type accepted by Tag ) .net wraps the value type with a new object ('boxes' it). int是一个值类型,将其转换为objectTag接受的类型) .net 用新的object ('boxes' it)包装值类型。 As object is a reference type and each tag has a different object the equality is not satisfied.由于object是引用类型,并且每个标签都有不同的 object,因此不满足相等性。

To make it work you must unbox the value, via a type cast or using the operator as :要使其工作,您必须通过类型转换或使用运算符as值拆箱:

//Unbox values before comparing
if (openBox1.Image.Tag as integer == openBox2.Image.Tag as integer)
    //...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM