如何简化以下代码:
try { var metadata = GetMetadata(); return metadata ?? _provider.GetLatestMetadata(guid); } catch (AuthenticationException) { return _provider.GetLatestMetadata(guid); } catch (HttpUnauthorizedRequestException) { return _provider.GetLatestMetadata(guid); } catch (WebException) { return _provider.GetLatestMetadata(guid); } catch (VcenterException) { return _provider.GetLatestMetadata(guid); }
我想避免代码重复.
可能吗?
如果您不想进行全能并且确实需要避免重复代码,则可以使用异常过滤器捕获特定异常:
try { var metadata = GetMetadata(); return metadata ?? _provider.GetLatestMetadata(guid); } catch (Exception ex) when ( ex is AuthenticationException || ex is HttpUnauthorizedRequestException || ex is WebException || ex is VcenterException ) { return _provider.GetLatestMetadata(guid); }