foreach (var item in mainCanvas.Children)
{
if (item is Button)
{
(item as Button).Content = "this is a button";
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用LINQ或.NET 4的其他功能来更简洁(可能是高性能的)吗?
Mar*_*ers 12
你可以使用Enumerable.OfType:
foreach (var button in mainCanvas.Children.OfType<Button>())
{
button.Content = "this is a button";
}
Run Code Online (Sandbox Code Playgroud)
性能测量
方法1:OPs原始建议
foreach (var item in mainCanvas.Children)
{
if (item is Button)
{
(item as Button).Content = "this is a button";
}
}
Run Code Online (Sandbox Code Playgroud)
方法2:OfType
foreach (var button in mainCanvas.Children.OfType<Button>())
{
button.Content = "this is a button";
}
Run Code Online (Sandbox Code Playgroud)
方法3:仅施放一次
foreach (var item in mainCanvas.Children)
{
Button button = item as Button;
if (button != null)
{
button.Content = "this is a button";
}
}
Run Code Online (Sandbox Code Playgroud)
方法4:for循环:
List<object> children = mainCanvas.Children;
for (int i = 0; i < children.Count; ++i)
{
object item = children[i];
if (item is Button)
{
(item as Button).Content = "this is a button";
}
}
Run Code Online (Sandbox Code Playgroud)
结果
Iterations per second Method 1: 18539180 Method 2: 7376857 Method 3: 19280965 Method 4: 20739241
结论
for循环代替,可以获得最大的改进foreach.OfType速度相当慢.但请记住首先优化可读性,并且只有在性能分析的情况下才会优化性能,并发现此特定代码是性能瓶颈.