C# 7 模式匹配语义 [英] C# 7 pattern matching semantics

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

问题描述

我有两个我认为相等的代码块:

首先是基于 if 的块

然后完全相同,但转换为在类型上切换大小写.(抱歉 Resharper 红色波浪线标记不好,Resharper 还不明白这一点)

基于 switch 的代码将在第一个不为 null 的 return Actor.Done 上抛出 Null 引用异常.

这是模式匹配错误还是我在这里遗漏了一些语义?

我已经找到了解决方法..

改变这一点:

case MessageEnvelope env:

case MessageEnvelope _:var env = m 作为 MessageEnvelope;

让一切顺利.所以这给我留下了一个问题,这些线条不应该完全相同吗?

解决方案

当您捕获(在 lambda 中)在 switch 语句中声明的模式变量时,这是一个已知错误.请参阅https://github.com/dotnet/roslyn/issues/16066>

I have the two blocks of code that I would like to think are equal:

First the if based block

Then the exact same but converted to switch case over types. (sorry for bad Resharper red squiggly markers, Resharper doesnt understand this yet)

The switch based code will throw a Null reference exception on the first return Actor.Done which is not null.

Is this a pattern match bug or is there some semantics that I am missing here?

[edit] I've found a fix for it..

Changing this:

case MessageEnvelope env:

to

case MessageEnvelope _:
    var env = m as MessageEnvelope;

Makes it all work. So that leaves me with the question, arn't those lines supposed to be exctly the same?

解决方案

This is a known bug when you capture (in a lambda) a pattern variable that was declared in a switch statement. See https://github.com/dotnet/roslyn/issues/16066

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

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