假设我有 Base
和 Child1
、Child2
、Child3
类,我有以下代码:
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));
}
请注意,在注释行中,我不需要这些 child2
、child3
变量,因为它具有什么类型并不重要,如果它不是 child1
.
Resharper 建议我可以安全地删除未使用的变量。有趣的部分来了。
我不能那样做:
case Child2: case Child3:
因为它导致“此时类名无效”语法错误。
这种用法似乎最适合我。我不能那样做:
case Child2 nevermind: case Child3 nevermind:
因为它会导致“冲突变量”错误。顺便说一句,如果
ProcessAnyOther
方法接受更精确的类型(Child2
和Child3
的基础)并且我用nevermind
参数而不是b
。但是,我可以做到:
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/