6 c#
我正在尝试计算给定路径的所有子文件夹中的文件总数.我正在使用递归函数调用.可能是什么原因?
码:
int iCount =0;
getFileCount(_dirPath, out iCount);
private void getFileCount(string _path, out int iCount )
{
try
{
// gives error :Use of unassigned out parameter 'iCount' RED Underline
iCount += Directory.GetFiles(_path).Length;
foreach (string _dirPath in Directory.GetDirectories(_path))
getFileCount(_dirPath, out iCount);
}
catch { }
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*eff 11
您希望ref参数不是out参数,因为您既接受该值又设置新值.
int iCount = 0;
getFileCount(_dirPath, ref iCount);
private void getFileCount(string _path, ref int iCount )
{
try
{
// gives error :Use of unassigned out parameter 'iCount' RED Underline
iCount += Directory.GetFiles(_path).Length;
foreach (string _dirPath in Directory.GetDirectories(_path))
getFileCount(_dirPath, ref iCount);
}
catch { }
}
Run Code Online (Sandbox Code Playgroud)
更好的是,根本不要使用参数.
private int getFileCount(string _path) {
int count = Directory.GetFiles(_path).Length;
foreach (string subdir in Directory.GetDirectories(_path))
count += getFileCount(subdir);
return count;
}
Run Code Online (Sandbox Code Playgroud)
甚至比这更好,不要创建一个函数来做框架已经内置的东西..
int count = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length
Run Code Online (Sandbox Code Playgroud)
并且我们没有做得更好......当你需要的只是一个长度时,不要浪费空间和周期创建一个文件数组.相反,列举它们.
int count = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Count();
Run Code Online (Sandbox Code Playgroud)