使用 IEnumerable<Exception> 自己的异常

我想自己做个例外,比如AggregateException:


var exceptions = ErrorCollectionExtension.GetErrorsAsExceptions(compiler.Errors);

throw new AggregateException("Error", exceptions);

可以作为参数List:Exceptions


public MyException(string message, IEnumerable<Exception> innerExceptions)

        : base(message, innerExceptions)

    {


    }

innerExceptions但是我在 base上遇到错误。


如何通过收集它来制作自己的例外AggregateException?


慕容708150
浏览 58回答 1
1回答

慕工程0101907

一种方法是Exception通过一组内部异常来简单地扩展类,有点像这样:public class MyException : Exception{&nbsp; &nbsp; private readonly ReadOnlyCollection<Exception> _innerExceptions;&nbsp; &nbsp; public MyException(string message, IEnumerable<Exception> innerExceptions)&nbsp; &nbsp; &nbsp; &nbsp; : base(message, innerExceptions.FirstOrDefault())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _innerExceptions = innerExceptions.ToList().AsReadOnly();&nbsp; &nbsp; }&nbsp; &nbsp; public ReadOnlyCollection<Exception> InnerExceptions => _innerExceptions;}或者你可以继承AggregateException并使用它的结构:public class MyException : AggregateException{&nbsp; &nbsp; public MyException(string message, IEnumerable<Exception> innerExceptions)&nbsp; &nbsp; &nbsp; &nbsp; : base(message, innerExceptions)&nbsp; &nbsp; {&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP