简体   繁体   English

C#7模式匹配语义

[英]C# 7 pattern matching semantics

I have the two blocks of code that I would like to think are equal: 我有两个我想认为相等的代码块:

First the if based block 首先是基于if的块 基于IF的代码

Then the exact same but converted to switch case over types. 然后完全相同,但转换为切换大小写类型。 (sorry for bad Resharper red squiggly markers, Resharper doesnt understand this yet) (对不好的Resharper红色波浪状标记感到抱歉,Resharper尚不了解这一点)

基于SWITCH的代码

The switch based code will throw a Null reference exception on the first return Actor.Done which is not null. 基于开关的代码将在第一个return Actor.Done时抛出Null引用异常,该异常不为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. 当您捕获(以lambda形式)在switch语句中声明的模式变量时,这是一个已知的错误。 See https://github.com/dotnet/roslyn/issues/16066 参见https://github.com/dotnet/roslyn/issues/16066

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM