如何将特定数量的标签添加到标签数组?

How to add a specific number of labels to a label array?

我一直在尝试将一些蜡烛添加到一个数组中,这样我就可以在我的其余代码中使用该数组,更轻松地使用蜡烛的属性。然而,我的代码似乎并不正确,我希望有人能帮助我解决这个问题。 (颜色 != DarkGoldenrod 将蜡烛与我项目中的其他标签区分开来,它们都具有相同的颜色)

private Label[] CandlesToMatrix()
    {
        Label[] candles = new Label[7];
        foreach (Control ctrl in this.Controls)
        {
            if ((ctrl is Label) && (ctrl.BackColor != Color.DarkGoldenrod))
            {
                for (int i = 0; i < 7; i++)
                {
                    candles[i] = (Label)ctrl;
                }
            }
        }
        return candles;

    }

您面临的问题是您为数组中的每个元素分配了符合条件的控件。

代码运行如下:枚举所有控件并检查它是否是标签而不是某种特定颜色。如果他找到一个,他将用对该控件的引用填充整个数组。如果数组已经被之前的匹配填满,它将被覆盖。

所以你最终得到一个数组,其中填充了空值或最后一个匹配的控件。

我认为您希望数组中充满 'unique' 控件。所以每次你找到一个匹配项,你必须增加索引来写入它。

例如:

private Label[] CandlesToMatrix()
{
    Label[] candles = new Label[7];

    // declare a variable to keep hold of the index
    int currentIndex = 0;

    foreach (Control ctrl in this.Controls)
    {
        if ((ctrl is Label label) && (label.BackColor != Color.DarkGoldenrod))
        {
            // check if the currentIndex is within the array. Never read/write outside the array.
            if(currentIndex == candles.Length)
                break;
                
            candles[currentIndex] = label;
            currentIndex++;
        }
    }
}

我再补充一个例子......

C# 提供的功能还有很多。这是一种有点旧的 C 编程风格。固定大小的数组等。在 C# 中,您还有一个列表,它使用您在 <> 之间使用的类型。例如。 List<Label>.

这是一个使用列表的例子。

private Label[] CandlesToMatrix()
{
    List<Label> candles = new List<Label>();
    
    // int currentIndex = 0;   You don't need to keep track of the index. Just add it.
    foreach (Control ctrl in this.Controls)
    {
        if ((ctrl is Label label) && (label.BackColor != Color.DarkGoldenrod))
        {
            candles.Add(label);
        }
    }
    
    return candles.ToArray(); // if you still want the array as result.
}

并且...您还可以使用 Linq(这是下一步)

private Label[] CandlesToMatrix()
{
    return this.Controls
        // check the type.
        .OfType<Label>()
        // matches it the creteria?
        .Where(label => ((ctrl is Label label) && (label.BackColor != Color.DarkGoldenrod))
        // fillup an array with the results
        .ToArray();
}