Try块内的收益率

时间:2013-05-26 09:20:39

标签: c# yield-return

我尝试使用递归的内置方法:

public IEnumerable<string> Foo(string path)
{
    try
    {
        foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
        {
            yield return file;
        }
    }
    catch (Exception)
    { }
}

并收到此错误:

  

无法使用catch子句在try块的主体中​​生成值

我如何使用try-catch以避免崩溃的方法是我没有文件夹权限?

1 个答案:

答案 0 :(得分:1)

public IEnumerable<string> Foo(string path)
{
    var files = new List<string>();
    try
    {
      files.AddRange(Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories));
    }
    catch (Exception)
    {
       // this is bad style. You should catch more specific exceptions
    }

    return files;
}