![](/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.