【问题标题】:Try-Catch with Yield return in a Recursive Method递归方法中带有收益返回的 Try-Catch
【发布时间】:2018-02-08 09:05:54
【问题描述】:

我需要在递归方法中实现 try catch,但我不知道该怎么做。这是代码:

    private IEnumerable <FileItem> FilesToDownload(FileItem file)
    {
        logger = LogManager.GetLogger(GetType());

        using (var wb = new WebDavSession(webDavUrl, new NetworkCredential(user, psw)))
        using (Task<IList<WebDavSessionItem>> task = wb.ListAsync(file.Path))
        {
            task.Wait();
            foreach (var item in task.Result)
            {
                FileItem retFile = item.ToFileItem();
                logger.Info("Going Into " + retFile.Path);
                if (item.IsFolder == true)  
                {
                    foreach (var inner in FilesToDownload(retFile))
                    {
                        yield return inner;
                    }
                }
                else
                {
                    yield return retFile;
                }
            }
        } 
    }

这种方法可以帮助我找到嵌套文件夹中的文件(在云中),所以递归是必要的。

你有什么建议?

【问题讨论】:

  • 建议什么?您在这里有什么具体问题吗?例如一些编译器错误?
  • 我认为更紧迫的问题是你打电话给task.Wait(); - 在某些情况下你可能会侥幸逃脱,但这绝对是不是你现在的样子意味着使用异步方法。不幸的是,“异步枚举”没有预先存在的模式 - 已经讨论过很多次但还没有正确结束
  • 我没有看到try...catch...
  • 添加 try/catch 时会发生什么?注意:编译器在这方面多年来一直在发展,因此询问以下问题也很重要:您使用的是什么编译器版本(或什么 IDE 版本,如果更容易的话)?
  • @MNeg 哦,确实如此,但这取决于你把它们放在哪里!

标签: c# methods try-catch ienumerable yield-return


【解决方案1】:

不能做的是有一个try/catch围绕一个yield return 声明 - 这违反了CS1626

但是:您仍然可以使用try/catch - 您只需要在布局中发挥创意。例如:

foreach (var item in task.Result)
{
    IEnumerable<FileItem> subItems = null;
    FileItem subItem = null;

    try
    {
        FileItem retFile = item.ToFileItem();
        logger.Info("Going Into " + retFile.Path);
        if (item.IsFolder == true)
        {
            subItems = FilesToDownload(retFile);
        }
        else
        {
            subItem = retFile;
        }
    }
    catch { /* your code here */ }
    if (subItem != null) yield return subItem;
    if (subItems != null)
    {
        foreach (var x in subItems) yield return x;
    }
}

其他想法:

  • Stack&lt;T&gt;Queue&lt;T&gt; 可能是比深度递归更合适的方法
  • task.Wait() 不好,可能会导致代码死锁;不幸的是,“异步枚举”目前没有好的模式

【讨论】:

    猜你喜欢
    • 2014-04-30
    • 2011-11-06
    • 2014-03-10
    • 1970-01-01
    • 2020-10-05
    • 2016-08-03
    • 2018-05-23
    • 2012-02-25
    • 2015-06-30
    相关资源
    最近更新 更多