递归函数内部的计数器 [英] Counter inside a recursive function
本文介绍了递归函数内部的计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要计算在此递归函数中删除的文件数。由于它是递归的,因此我不能使用 if
语句,并且C#不支持全局变量。
I need to count the number of files deleted in this recursive function. Since it's recursive I cannot use if
statements, and C# does not support global variables. Any alternatives?
static void DirSearch(string path)
{
try
{
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
//count++
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
DirSearch(dirPath);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
推荐答案
一个方式是传递一些东西以供计数。我会使用 ref
来做到这一点,例如:
One way is to pass in something for it to count into. I'd do this using ref
, for example:
static void DirSearch(string path, ref int count)
{
try
{
foreach (string dirPath in Directory.GetDirectories(path))
{
foreach (string filePath in Directory.GetFiles(dirPath))
{
string filename = Path.GetFileName(filePath);
if (filename.Equals("desktop.txt"))
{
File.Delete(filePath);
count++
}
Console.WriteLine(filePath); // print files
}
Console.WriteLine(dirPath); // print directories
DirSearch(dirPath,ref count);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}
然后称呼它:
int count = 0;
DirSearch(@"C:\SomePath",ref count);
然后,您可以像平常一样使用 count
您已在代码中注释掉了。
Then you can use count
as normal as you had commented out in your code.
这篇关于递归函数内部的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文