C# 7.0 不带变量的类型模式匹配用法
C# 7.0 type pattern matching usage without variable
假设我有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:
因为它会导致 "class name is not valid at this point" 语法错误。
这种用法似乎最适合我。
我做不到:
case Child2 nevermind:
case Child3 nevermind:
因为它会导致 "conflicting variable" 错误。顺便说一句,如果 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.)
通过命名变量 _
你告诉编译器你将永远不会再访问这个变量,所以它可以忽略你在前两个版本中遇到的问题。
假设我有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:
因为它会导致 "class name is not valid at this point" 语法错误。
这种用法似乎最适合我。我做不到:
case Child2 nevermind: case Child3 nevermind:
因为它会导致 "conflicting variable" 错误。顺便说一句,如果
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.)
通过命名变量 _
你告诉编译器你将永远不会再访问这个变量,所以它可以忽略你在前两个版本中遇到的问题。