0

我有一个由其他人创建的 VB Windows 程序,它被编程以便任何人都可以通过使用类库添加到程序的功能,程序调用它们(即......类库,DLL 文件)插件,我正在创建的插件是一个 C# 类库。即..dll

我正在开发的这个特定插件以标签的形式添加了一个简单的日期时间时钟功能,并将其插入到 3 深的面板中。我已经测试过的代码并且它有效。我的问题是:有更好的方法吗?例如,我使用 Controls.Find 3 个不同的时间,每次我知道我在寻找什么面板时,只会将一个面板添加到 Control[] 数组中。因此,我再次对仅包含单个元素 3 次不同时间的数组进行 foreach。

现在就像我说的那样,代码可以正常工作并按我的预期工作。它似乎过于冗长,我想知道是否可能存在性能问题。

这是代码:

    foreach (Control p0 in mDesigner.Controls)
        if (p0.Name == "Panel1")
        {
            Control panel1 = (Control)p0;
            Control[] controls = panel1.Controls.Find("Panel2", true);

            foreach (Control p1 in controls)
            if (p1.Name == "Panel2")
            {
                Control panel2 = (Control)p1;
                Control[] controls1 = panel2.Controls.Find("Panel3", true);
                foreach(Control p2 in controls1)
                    if (p2.Name == "Panel3")
                    {
                        Control panel3 = (Control)p2;
                        panel3.Controls.Add(clock);
                    }
             }
         }
4

2 回答 2

0

使用以下功能

   public static Control FindControlRecursive(Control control, string id)
    {
        if (control == null) return null;
        Control ctrl = control.FindControl(id);
        if (ctrl == null)
        {
            foreach (Control child in control.Controls)
            {
                ctrl = FindControlRecursive(child, id);
                if (ctrl != null) break;
            }
        }
        return ctrl;
    }
}

接着

Control panel3 = FindControlRecursive(mDesigner.Controls, "Panel3");
于 2012-09-30T02:57:29.627 回答
0

使用 Andrei 共享的概念,我能够制定出一种方法,该方法不仅适用于我想添加到面板的标签,而且还允许我从另一个方法调用它,该方法只需修改两个的大小和位置其他控件,使此功能非常可重用。

private Control FindControlRecursive(Control ct, string id)
{
    Control[] c;
    Control ctr;

    if (ct == null)
        c = mDesigner.Controls.Find(id, true);
    else
        c = ct.Controls.Find(id, true);

    foreach (Control child in c)
    {
        if (child.Name == id)
        {
            ctr = child;
            return ctr;
        }
        else
        {
            ctr = FindControlRecursive(child, id);
            if (ctr != null)
                return ctr;
        }
    }
    return null;
}

调用代码如下所示:

Control ct = null;
Control panel3 = FindControlRecursive(ct, "Panel3");

// and Here is where I can Add controls or even change control properties.
if (panel3 != null)
    panel3.Controls.Add(clock);

谢谢您的帮助...

于 2012-09-30T06:34:10.913 回答