![](/img/trans.png)
[英]I have an array of colors and I want to assign the colors with the labels in the for loop in C#. How can I do so?
[英]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
我正在用C#做一个小游戏。 但是我的表单中有很多标签,如果对象与标签之一绑定,则它最多会返回一个文本框,但是编写它的代码太多。 那么,如何给所有标签起一个名字呢?
这就是我现在所拥有的,但是当我移动对象(标签)时,它将显示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;
}
}
此逻辑是否适用于表单上的每个Label
? 如果是这样,则可以在“ Controls
集合中动态找到它们。 也许是这样的:
foreach (var label in this.Controls)
if (label is Label)
if (player.Bounds.IntersectsWith((label as Label).Bounds))
{
MessageBox.Show("hi");
break;
}
或没有循环和嵌套:
if (this.Controls.Where(c => c is Label).Any(c => player.Bounds.IntersectsWith((c as Label).Bounds)))
MessageBox.Show("hi");
或者,如果仅对此应用标签的子集 ,则可以将它们显式存储在类的集合中(也许在构造函数中),然后在该集合上循环。 逻辑相同,但是您将遍历集合而不是this.Controls
。
根据要抽象多少,另一种选择是创建自己的类(也许称为IntersectableLabel
),该类继承自Label
。 使该类的所有相关标签实例都代替Label
。 (我不确定这可能会对表单设计者产生什么影响,因为我使用Windows Forms已经很长时间了。)然后可以遍历this.Controls
并查找is IntersectableLabel
,它将过滤掉任何您不想使用的标签。
请注意,如果标签曾经嵌套在其他控件中,则可能需要递归函数而不是简单的循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.