C# 7.0 不带变量的类型模式匹配用法

标签 c# pattern-matching c#-7.0

假设我有 BaseChild1Child2Child3 类,我有以下代码:

Base b; // value is acquired
switch (b) 
{
    case Child1 child1:
        ProcessChild1(child1);
        break;

    case Child2 child2:
    case Child3 child3:
        ProcessAnyOther(b); // <--
        break;

    default:
        throw new ArgumentOutOfRangeException(nameof(b));
}

请注意,在注释行中,我不需要这些 child2child3 变量,因为它具有什么类型并不重要,如果它不是 child1.
Resharper 建议我可以安全地删除未使用的变量。有趣的部分来了。

  1. 我不能那样做:

    case Child2:
    case Child3:
    

    因为它导致“此时类名无效”语法错误。
    这种用法似乎最适合我。

  2. 我不能那样做:

    case Child2 nevermind:
    case Child3 nevermind:
    

    因为它会导致“冲突变量”错误。顺便说一句,如果 ProcessAnyOther 方法接受更精确的类型(Child2Child3 的基础)并且我用 nevermind 参数而不是 b

  3. 但是,我可以做到:

    case Child2 _:
    case Child3 _:
    

    它甚至不创建“_”变量。 这正是 Resharper 建议要做的。

我的问题是:这是什么?它还能用在什么地方?这个“_”运算符或语言部分是如何调用的?它是 C# 语言规范的一部分吗?

最佳答案

它叫做 discard是的,它是 C#7 规范的一部分。

来自链接的文章:

Discards are local variables which you can assign but cannot read from. i.e. they are “write-only” local variables. They don’t have names, instead, they are represented as a _ is a contextual keyword, it is very similar to var, and _ cannot be read (i.e. cannot appear on the right side of an assignment.)

通过将变量命名为 _,您告诉编译器您将永远不会再访问该变量,因此它可以忽略您在前两个版本中遇到的问题。

关于C# 7.0 不带变量的类型模式匹配用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45915985/

相关文章:

recursion - 在 Elixir 中使用模式匹配和递归拆分列表

Haskell 模式匹配对称情况

c# - "Use of unassigned local variable"错误的原因是什么?

c# - 在 Win8 XAML 中使用 SemanticZoom 对分组 GridView 中的滚动使用react

c# - XamlReader.Load() 编码

image-processing - 使用 OpenCV 进行模式识别

c# - 使用 var/null 奇怪的行为进行切换

c# - 将 expression-bodied 与 throw 混合用于多个参数

c# - 奇数返回语法语句

c# - 如何重定向到同一 Controller 的索引页面