[英]How do I define a while loop in a function and call it multiple times in C#?
我有while
循环
string path = "";
int ctr = 0, i = 0;
while (i < lvwArticles.Items.Count)
{
ListViewItem lvi = lvwArticles.Items[i];
if (lvi.SubItems[2].Text != path)
{
path = lvi.SubItems[2].Text;
ctr = 0;
skipme = false;
}
if (!skipme)
{
ctr++;
lvi.EnsureVisible();
lvi.Checked = true;
}
//Process
i++;
}
private void function1()
{
while()
{
//Process
}
}
private void function2()
{
while()
{
//Process
}
}
private void function3()
{
while()
{
//Process
}
}
private void function4()
{
while()
{
//Process
}
}
private void function5()
{
while()
{
//Process
}
}
我的程序中有5个functions
需要while
循环。 因此,有没有一种方法可以在单独的函数中声明while
循环,并在需要时调用它?
//Process
是变量。 因此,我在不同的函数中有多个不同的动作,但是所有这些动作都需要在同一while
循环内完成。
// Process是变量。 因此,我在不同的函数中有多个不同的动作,但是所有这些动作都需要在同一while循环内完成。
是的你可以。 这称为Action
:
public void YourFunction(Action action)
{
string path = "";
int ctr = 0, i = 0;
while (i < lvwArticles.Items.Count)
{
ListViewItem lvi = lvwArticles.Items[i];
if (lvi.SubItems[2].Text != path)
{
path = lvi.SubItems[2].Text;
ctr = 0;
skipme = false;
}
if (!skipme)
{
ctr++;
lvi.EnsureVisible();
lvi.Checked = true;
}
//Process
action();
i++;
}
}
现在,您可以传递此时要执行的过程:
YourFunction(() => MessageBox.Show("Hello"));
我的程序中有5个函数需要while循环。 因此,有没有一种方法可以在单独的函数中声明while循环,并在需要时调用它?
这是为了演示我在评论中询问的递归行为:
private void LoadTree(ListView lstViewChild)
{
string path = "";
int ctr = 0, i = 0;
while (i < lstViewChild.Count)
{
ListViewItem lvi = lstViewChild.Items[i];
if (lvi.SubItems[2].Text != path)
{
path = lvi.SubItems[2].Text;
ctr = 0;
skipme = false;
//I think its here where you want to recursively call it
LoadTree(lvi); //<-- here we call this method again, be careful as each time you call it, it add to the call stack and when you exhaust that it results in a STACKOVERFLOW exception!
}
if (!skipme)
{
ctr++;
lvi.EnsureVisible();
lvi.Checked = true;
}
//Process
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.