C# 7 模式匹配 [英] C# 7 Pattern Matching

查看:58
本文介绍了C# 7 模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下异常过滤器

Suppose I have the following exception filter

try {
    ...
} catch (Exception e) when (e is AggregateException ae && ae.InnerException is ValueException<int> ve || e is ValueException<int> ve) {
    ...
}

我可以简单地编写两个单独的 catch 块,但我想看看如何使用模式匹配功能来捕获本身或包裹在 AggregateException 中.然而,这里编译器抱怨 ve 的重新定义,这是可以理解的.我见过这样一种情况,其中模式匹配的变量在相同的表达式中重复使用,如下所示:https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

I could have simply written two separate catch blocks, but I wanted to see how one could use the pattern matching feature to catch an exception that either is itself or is wrapped within an AggregateException. Here, however, the compiler complains of a redefinition of ve, which is understandable. I have seen a case where a pattern matched variable is reused within the same expression as shown here: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

if (o is int i || (o is string s && int.TryParse(s, out i)) { /* use i */ }

所以可能有一种方法可以做我想做的事.或者有吗?

so there is probably a way to do what I want. Or is there?

推荐答案

您不能在同一范围内两次声明 ve 变量.但是您可以重写异常过滤器,以便 ValueException 的变量将只声明一次:

You cannot declare ve variable twice in same scope. But you can rewrite exception filter so that variable for ValueException<int> will be declared only once:

catch(Exception e) 
  when (((e as AggregateException)?.InnerException ?? e) is ValueException<int> ve)
{
   // ...
}

如果异常被直接抛出或被包装到AggregateException 中,那么它是您的单线捕获异常.

It's your one-liner to catch exception if it either was thrown directly or if it is wrapped into AggregateException.

请记住,AggregateException 的目的是将多个异常合并为一个异常对象.可能有几个内部异常,其中一些也可以是聚合异常.因此,您应该展平聚合异常并检查其所有内部异常.

Keep in mind that purpose of AggregateException is consolidating multiple exceptions into one exception object. There could be several inner exceptions, and some of them can be aggregate exceptions as well. So you should flatten aggregate exception and check all of its inner exceptions.

您可以将解包"部分放入扩展方法中以提高代码的可读性.

You can put 'unwrapping' part into extension method to improve readability of your code.

这篇关于C# 7 模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆