Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何解决未分配';输出';参数错误?_C# - Fatal编程技术网

C# 如何解决未分配';输出';参数错误?

C# 如何解决未分配';输出';参数错误?,c#,C#,我正在尝试计算给定路径的所有子文件夹中的文件总数。我正在使用递归函数调用。原因可能是什么 代码: 您需要的是ref参数,而不是out参数,因为您同时接受该值并设置一个新值 int iCount = 0; getFileCount(_dirPath, ref iCount); private void getFileCount(string _path, ref int iCount ) { try { // gives error :Use

我正在尝试计算给定路径的所有子文件夹中的文件总数。我正在使用递归函数调用。原因可能是什么

代码:


您需要的是
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 { }
}
更好的是,根本不使用out参数

private int getFileCount(string _path) {
    int count = Directory.GetFiles(_path).Length;
    foreach (string subdir in Directory.GetDirectories(_path))
        count += getFileCount(subdir);

    return count;
}       
甚至比这更好的是,不要创建一个函数来完成框架内置的功能

int count = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length
而且我们还没有好起来。。。当您只需要一个长度时,不要浪费空间和周期来创建文件数组。而是列举它们

int count = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Count();

作为输出传递的参数需要在函数中初始化。由于iCount尚未初始化,因此该值未知,并且不知道从何处开始,即使它是一个默认值为0的整数


我建议不要将out参数与递归函数耦合在一起。相反,可以使用常规返回参数。微软自己通过一些静态分析规则提出建议。

已经在main/global中声明了iCount?为什么不能让方法返回值,而不是将其作为out传递?你收到的错误消息是什么?更重要的是,你需要在递归的顶部赋值零(f.e.为0)。更新后,我忘了写这个问题,我已经赋值零来计数variable@user3732729既然您将iCount声明为
out
,那么在从方法引用()返回之前,您需要设置它。我已经检查了这个问题,但没有帮助我。感谢大家的快速响应。感谢回答,我尝试了Ref函数,但在函数调用时出错,而且我不必使用任何内置函数。当您将函数更改为
Ref
时,您还需要将调用更改为
Ref
,并且需要在调用之前初始化变量。表示“方法必须具有返回类型”在getFileCount(_dirPath,ref iCount);我这么做了,但运气不好,如果可以的话,请删除副本。。
int count = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories).Count();