【问题标题】:Turning a list of objects into a nested set of objects with iteration通过迭代将对象列表转换为嵌套对象集
【发布时间】:2014-03-25 16:45:11
【问题描述】:

所以,我有一个对象列表,在本例中为ExceptionInfo。这些对象包含要放入异常对象的信息。但是,异常是嵌套的,分配 Exception 对象的InnerException 属性的唯一方法是在构造时指定它。

所以,我喜欢这样:

    static Exception ListToNestedExceptions(List<ExceptionInfo> l, int index=0)
    {
        if (index > l.Count)
        {
            return null;
        }
        var e = new Exception("", ListToNestedExceptions(l, ++index));
        e.Data[ExceptionDataKeys.StackTrace] = l[index].Stacktrace;
        return e;
    }

我知道理论上可以通过迭代来完成所有可以通过递归实现的事情,但是,我看不出这将如何应用在这里。我对这个版本很好,但出于好奇,有没有可能把它变成一个交互式版本?此外,这甚至可以应用尾调用优化吗?

【问题讨论】:

    标签: c# recursion nested iteration


    【解决方案1】:

    尝试以下不递归的示例。主要思想是从列表中的最后一个ExceptionInfo 向下迭代到第一个。

    public class ExceptionInfo
    {
        public string Message;
    }
    
    public static Exception MakeException(List<ExceptionInfo> list)
    {
        if (list == null || list.Count == 0)
            throw new ArgumentNullException("list");
    
        Exception ex = new ApplicationException(list.Last().Message);
        if (list.Count >= 2)
            for (int i = list.Count - 2; i >= 0; i--)
                ex = new Exception(list[i].Message, ex);
        return ex;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 2020-07-14
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      相关资源
      最近更新 更多