-1

我已经通过 stasckoverflows 了解了如何遍历标签数组(Label[] A 下面)。我对如何同时遍历标签 A 和标签 B 感到困惑,这样我就可以使用相同的代码。请注意,我可以使用两个 foreach 循环,但我计划拥有相当多的标签数组(Label[]A -> Labbel[] XXX)。

Label[] A = { A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13,A14, A15, A16, A17, A18, A19, A20, A21, A22, A23, A24, A25, A26, A27, A28, A29, A30, A31, A32, A33, A34, A35, A36, A37, A38, A39, A40, A50, A51, A52, A53, A54, A55, A56, A57, A58, A59, A60 };
            Label[] B = { B1, B2, B3, B4, B5, B6, B7, B8, B9, B10, B11, B12, B13, B14, B15, B16, B17, B18, B19, B20, B21, B22, B23, B24, B25, B26, B27, B28, B29, B30, B31, B32, B33, B34, B35, B36, B37, B38, B39, B40, B50, B51, B52, B53, B54, B55, B56, B57, B58, B59, B60 };
            Graphics g = this.CreateGraphics();
            Pen pen = new Pen(Color.Blue, 1);
            g.DrawRectangle(pen, RectangleDrawer.rect_x, RectangleDrawer.rect_y, RectangleDrawer.rect_w, RectangleDrawer.rect_z);

            foreach (Label l in A)
            {
                if (l.Location.X > RectangleDrawer.rect_x && l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
                    l.Location.Y > RectangleDrawer.rect_y && l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
                {
                    l.BackColor = col;
                }

您能提供的任何帮助将不胜感激。

4

1 回答 1

0

您可以有一个数组来保存标签的所有数组,然后执行以下操作:

foreach (Label[] labels in LabelsArrays)
{
    foreach (Label l in labels)
    {
        if (l.Location.X > RectangleDrawer.rect_x &&
            l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
            l.Location.Y > RectangleDrawer.rect_y &&
            l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
        {
            l.BackColor = col;
        }
    }
}

或者您可以使用 LINQ 扩展方法并执行以下操作:

foreach (Label l in labelsA.Union(labelsB).Union(labelC))
{
    if (l.Location.X > RectangleDrawer.rect_x &&
        l.Location.X < (RectangleDrawer.rect_x + RectangleDrawer.rect_w) - 25 &&
        l.Location.Y > RectangleDrawer.rect_y &&
        l.Location.Y < (RectangleDrawer.rect_y + RectangleDrawer.rect_z) - 25)
    {
        l.BackColor = col;
    }
}
于 2012-04-19T07:45:31.640 回答