ControlCollection扩展方法优化
有关于我编写的扩展方法的问题,如下所示:
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance) where T : class
{
T control;
foreach (Control ctrl in instance)
{
if ((control = ctrl as T) != null)
{
yield return control;
}
foreach (T child in FindControlsOfType<T>(ctrl.Controls))
{
yield return child;
}
}
}
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance, Func<T, bool> match) where T : class
{
return FindControlsOfType<T>(instance).Where(match);
}
这里的想法是在控件集合中查找与特定条件匹配的所有控件(因此是 Func<..>)。我的问题是:
第二个方法(具有 Func)是否首先调用第一个方法来查找类型 T 的所有控件,然后执行 where 条件,或者“运行时”优化调用以在“整个”枚举(如果你明白我的意思)。
其次,我还可以对代码进行其他优化以使其性能更好吗?
一个例子如下:
var checkbox = this.Controls.FindControlsOfType<MyCustomCheckBox>(
ctrl => ctrl.CustomProperty == "Test"
)
.FirstOrDefault();
got question regarding an extension method that I have written that looks like this:
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance) where T : class
{
T control;
foreach (Control ctrl in instance)
{
if ((control = ctrl as T) != null)
{
yield return control;
}
foreach (T child in FindControlsOfType<T>(ctrl.Controls))
{
yield return child;
}
}
}
public static IEnumerable<T> FindControlsOfType<T>(this ControlCollection instance, Func<T, bool> match) where T : class
{
return FindControlsOfType<T>(instance).Where(match);
}
The idea here is to find all controls that match a specifc criteria (hence the Func<..>) in the controls collection. My question is:
Does the second method (that has the Func) first call the first method to find all the controls of type T and then performs the where condition or does the "runtime" optimize the call to perform the where condition on the "whole" enumeration (if you get what I mean).
secondly, are there any other optimizations that I can do to the code to perform better.
An example can look like this:
var checkbox = this.Controls.FindControlsOfType<MyCustomCheckBox>(
ctrl => ctrl.CustomProperty == "Test"
)
.FirstOrDefault();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它会运行您的第一个方法(迭代器)来查找所有控件,但它会一次检查一个值。也就是说,它将找到一个控件,使用Where 子句检查它,找到下一个,检查它等等。我真的看不到算法中的任何优化 - 无论你做什么,你都必须检查每个控件(一次),这就是你正在做的事情。
It would run your first method (the iterator) to find all the controls, yes, but it would check one value at a time. That is, it would find one control, check it using the Where clause, find the next, check it and so on. I can't really see any optimisations in the algorithm - whatever you do you have to check every control (once) and that is what you're doing.