加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#7.0类型模式匹配用法没有变量

发布时间:2020-12-16 05:00:05 所属栏目:百科 来源:网络整理
导读:假设我有Base和Child1,Child2,Child3类,我有以下代码: Base b; // value is acquiredswitch (obj) { case Child1 child1: ProcessChild1(child1); break; case Child2 child2: case Child3 child3: ProcessAnyOther(b); // -- break; default: throw new Ar
假设我有Base和Child1,Child2,Child3类,我有以下代码:
Base b; // value is acquired
switch (obj) 
{
    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.)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读