【发布时间】:2015-08-10 22:25:54
【问题描述】:
我想从任何 ControlCollection 中获取所有相应类型的控件。重要的是要知道,我将一些元数据存储在控件的 Tag 属性中。 下面是我取回对应T类型控件的方法:
public static void GetAllChildControls<T>(Control.ControlCollection root, List<T> list) where T : Control {
if (list == null)
list = new List<T>();
foreach (Control ctl in root) {
if (ctl.GetType() == typeof(T))
list.Add((T)ctl);
if (ctl.Controls.Count > 0)
GetAllChildControls(ctl.Controls, list);
}
}
我写这篇文章的唯一原因是因为我没有取回 Tag 的值。在 VS2008 中 (T)ctl 没有可评估的标签(和 ContextMenu 也是如此)。它显示“无法评估表达式”。否则所有其他事情似乎都可以。
更新
我询问 Tag 属性的代码:
...
List<Button> list = null;
Helper.GetAllChildControls<Button>(master.ChildControls, list);
if (list != null)
foreach (CounterItem c in counters) {
Button b = list.Single(e => e.Tag.Equals(c.Name));
^^^
if (b == null)
continue;
b.SetCounter(c.Value);
}
...
【问题讨论】:
-
贴出你使用 Tag 属性的代码
-
@E-Bat 完成,帖子已更新
-
您遇到的行为/错误是什么?
-
是编译异常?运行?。顺便说一句,请注意 if (b == null) 行永远不会被评估为 Single linq 方法如果找不到匹配项会引发异常,也许您需要更改为 SingleOrDefault
-
我通过评估 e.Tag 得到运行时错误“无法评估表达式”。顺便说一句 b == null 真的没有意义......
标签: winforms .net-3.5 compact-framework