加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何解决未分配的’out’参数错误?

发布时间:2020-12-15 08:34:38 所属栏目:百科 来源:网络整理
导读:参见英文答案 Difference between ref and out parameters in .NET 18个 我正在尝试计算给定路径的所有子文件夹中的文件总数.我正在使用递归函数调用.可能是什么原因? 码: int iCount =0; getFileCount(_dirPath,out iCount);private void getFileCount(st
参见英文答案 > Difference between ref and out parameters in .NET 18个
我正在尝试计算给定路径的所有子文件夹中的文件总数.我正在使用递归函数调用.可能是什么原因?

码:

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 { }
}

解决方法

您希望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 { }
}

更好的是,根本不要使用参数.

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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读