简体   繁体   中英

C#. How can I give all labels in my form the same name, so if an object bounds with one of the labels that it will show something

I am making a little game with c#. But i have a lot of labels in my form and if an object bounds with one of the labels it most return a textbox, but it is too much code to write that. So, how can I give all the labels one name?

This is what I have now, but when I move my object(label) it will show MessageBoxes without Boundsing with other labels:

private void timer1_Tick(object sender, EventArgs e)
        {
            if (mUp == true) player.Top -= 1;
            if (mDown == true) player.Top += 1;
            if (mLeft == true) player.Left -= 1;
            if (mRight == true) player.Left += 1;

            foreach (var allLabels in this.Controls)
                if (allLabels is Label)
                    if (player.Bounds.IntersectsWith((allLabels as Label).Bounds))
                    {
                        MessageBox.Show("hi");
                        break;
                    }
        }

this is what happens if I set a breakpoint on the MessageBox.Show line.

Does this logic apply to every Label on the form? If so then you can find them dynamically in the Controls collection. Perhaps something like this:

foreach (var label in this.Controls)
    if (label is Label)
        if (player.Bounds.IntersectsWith((label as Label).Bounds))
        {
            MessageBox.Show("hi");
            break;
        }

Or without the loops and nesting:

if (this.Controls.Where(c => c is Label).Any(c => player.Bounds.IntersectsWith((c as Label).Bounds)))
    MessageBox.Show("hi");

Or if there's only a subset of labels to which this applies then you can store them explicitly in a collection on the class (perhaps in the constructor) and then loop over that collection. Same logic, but you'd loop over your collection instead of over this.Controls .

Depending on how much you want to abstract this, another option could be to create your own class (perhaps called something like IntersectableLabel ) which inherits from Label . Make all of your relevant labels instances of that class instead of Label . (I'm not sure what effect this may have on the forms designer honestly, it's been a very long time since I've used Windows Forms.) Then you can loop over this.Controls and look for is IntersectableLabel , which would filter out any labels you don't want to use.

Note that if your labels are ever nested in other controls then you may need a recursive function instead of a simple loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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