C#,请帮助将我的foreach循环更改为for循环 [英] C#, pls help to change my foreach loop to for loop
本文介绍了C#,请帮助将我的foreach循环更改为for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将foreach循环更改为for循环。我需要测量它们之间的性能。
谢谢
我尝试过:
How can I change my foreach loop to for loop. I need to measure the performance between them.
thanks
What I have tried:
public void ClearAllTextBoxes(Control controls)
{
foreach (Control control in controls.Controls)
{
if (control is TextBox)
{
((TextBox)control).Clear();
}
if (control.HasChildren)
{
ClearAllTextBoxes(control);
}
}
}
推荐答案
(未经测试)
(Not tested)
public void ClearAllTextBoxes(Control controls)
{
int n;
for (n=0; n<controls.Controls.Count; ++n)
{
Control control = control.Controls[n];
if (control is TextBox)
{
((TextBox)control).Clear();
}
if (control.HasChildren)
{
ClearAllTextBoxes(control);
}
}
}
以下内容:
Something along the line of:
for(int i = 0; i < controls.Controls.Count; i++){
if (controls.Controls[i] is TextBox)
{
((TextBox)controls.Controls[i]).Clear();
}
if (controls.Controls[i].HasChildren)
{
ClearAllTextBoxes(controls.Controls[i]);
}
}
这是记录在案的,是基本的.Net知识。
This is documented and is basic .Net knowledge.
>
此版本使用最现代的C#形式。
This version uses the most modern form of C#.
public void ClearAllTextBoxes(Control controls)
{
for (int n = 0; n < controls.Controls.Count; n++)
{
var control = control.Controls[n];
if (control is TextBox textBox)
{
textBox.Clear();
}
if (control.HasChildren)
{
ClearAllTextBoxes(control);
}
}
}
这篇关于C#,请帮助将我的foreach循环更改为for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文