[英]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#. 我正在用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: 这就是我现在所拥有的,但是当我移动对象(标签)时,它将显示MessageBoxes,而不会与其他标签发生界限:
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. 如果我在MessageBox.Show行上设置断点,就会发生这种情况。
Does this logic apply to every Label
on the form? 此逻辑是否适用于表单上的每个
Label
? If so then you can find them dynamically in the Controls
collection. 如果是这样,则可以在“
Controls
集合中动态找到它们。 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
. 逻辑相同,但是您将遍历集合而不是
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
. 根据要抽象多少,另一种选择是创建自己的类(也许称为
IntersectableLabel
),该类继承自Label
。 Make all of your relevant labels instances of that class instead of Label
. 使该类的所有相关标签实例都代替
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. (我不确定这可能会对表单设计者产生什么影响,因为我使用Windows Forms已经很长时间了。)然后可以遍历
this.Controls
并查找is IntersectableLabel
,它将过滤掉任何您不想使用的标签。
Note that if your labels are ever nested in other controls then you may need a recursive function instead of a simple loop. 请注意,如果标签曾经嵌套在其他控件中,则可能需要递归函数而不是简单的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.