西部数码 成品网站,网站备案号怎么查询,html5网站强制横屏,动漫做3d游戏下载网站有哪些咨询区 Jader Dias#xff1a;先上例子:myEnumerable.Select(a ThisMethodMayThrowExceptions(a));如何让上面的 Linq查询 即使在抛出异常的情况下也能完整的执行#xff0c;就像那种带有默认值的 try...catch 一样#xff0c;当异常抛出时总会执行 catch 后再把它救回… 咨询区 Jader Dias先上例子:
myEnumerable.Select(a ThisMethodMayThrowExceptions(a));如何让上面的 Linq查询 即使在抛出异常的情况下也能完整的执行就像那种带有默认值的 try...catch 一样当异常抛出时总会执行 catch 后再把它救回来。回答区 Stefan Steinegger
myEnumerable.Select(a {try{return ThisMethodMayThrowExceptions(a));}catch(Exception){return defaultValue;}});本质上来说上面这段代码大体上能解决你的问题但有一些坏味道。LeBaptiste我自己写了一些 扩展方法 可以捕获 IEnumerableT 中每一个迭代项的异常。用法
public void Test()
{Liststring completedProcesses initialEnumerable.SelectTry(x RiskyOperation(x)).OnCaughtException(exception { _logger.Error(exception); return null; }).Where(x x ! null) // filter the ones which failed.ToList();
}扩展方法
public static class OnCaughtExceptionExtension
{public static IEnumerableSelectTryResultTSource, TResult SelectTryTSource, TResult(this IEnumerableTSource enumerable, FuncTSource, TResult selector){foreach (TSource element in enumerable){SelectTryResultTSource, TResult returnedValue;try{returnedValue new SelectTryResultTSource, TResult(element, selector(element), null);}catch (Exception ex){returnedValue new SelectTryResultTSource, TResult(element, default(TResult), ex);}yield return returnedValue;}}public static IEnumerableTResult OnCaughtExceptionTSource, TResult(this IEnumerableSelectTryResultTSource, TResult enumerable, FuncException, TResult exceptionHandler){return enumerable.Select(x x.CaughtException null ? x.Result : exceptionHandler(x.CaughtException));}public static IEnumerableTResult OnCaughtExceptionTSource, TResult(this IEnumerableSelectTryResultTSource, TResult enumerable, FuncTSource, Exception, TResult exceptionHandler){return enumerable.Select(x x.CaughtException null ? x.Result : exceptionHandler(x.Source, x.CaughtException));}public class SelectTryResultTSource,TResult{internal SelectTryResult(TSource source, TResult result, Exception exception){Source source;Result result;CaughtException exception;}public TSource Source { get; private set; }public TResult Result { get; private set; }public Exception CaughtException { get; private set; }}
}如果还想完美一点可以再实现一个 SkipOnException, 接收可以忽略的异常。点评区 回答区的两个答案第一种方法简单粗暴但各位也能体会出这种写法的生硬之处第二种写法就比较????????了让我想起了强大的 Polly (基于.NET的弹性及瞬态故障处理库)各种眼花缭乱的玩法大家有兴趣可以看一看: https://github.com/App-vNext/Polly原文链接https://stackoverflow.com/questions/1294251/is-it-possible-to-handle-exceptions-within-linq-queries