简体   繁体   English

落在模式匹配中

[英]Fall through in pattern matching

currently in c#7 (version 15.3.4) following code is valid to compile but both variables are legitimately unusable. 目前在c#7(版本15.3.4)中,以下代码对编译有效,但两个变量都是合法不可用的。

switch(fruit)
{
    case Apple apple:
    case Orange orange:
    // impossible to use apple or orange
    break;
    case Banana banana:
    break;
}

If you try to use them, you get familiar error, variable might not be initialized before accessing. 如果您尝试使用它们,则会得到熟悉的错误,在访问之前可能无法初始化变量。

Some times in pattern matching you don't care about exact type, as long as that type is in category that you want. 有时在模式匹配中,您不关心确切的类型,只要该类型属于您想要的类别。 here only apples and oranges as an example. 这里只以苹果和橘子为例。

List<Fruit> applesAndOranges = new List<Fruit>();
switch(fruit)
{
    case Fruit X when X is Apple || X is Orange:
    applesAndOranges.Add(X);
    break;
    case Banana banana:
    break;
}

Are there better approaches? 有更好的方法吗?

You can use discards if you don't like to make garbage local variables in current region. 如果您不想在当前区域中创建垃圾局部变量,则可以使用丢弃。 then you can use switched variable directly. 那么你可以直接使用开关变量。 you may need additional cast if switched variable is of super class like object or something else. 如果切换变量是像对象或其他类似的超类,则可能需要额外的强制转换。

List<Fruit> applesAndOranges = new List<Fruit>();
switch(fruit)
{
    case Apple _:
    case Orange _:
    applesAndOranges.Add(fruit);
    break;
    case Banana banana:
    break;
}

I don't know how pattern matching is compiled. 我不知道如何编译模式匹配。 if it makes use of jump tables then this approach could be also a little faster. 如果它使用跳转表,那么这种方法也可以更快一些。 performance is not my concern though. 虽然表现不是我关注的问题。 this is more readable. 这更具可读性。

I'm already pleased by both solutions, so this is Q&A post that I liked to share. 我已经对这两种解决方案感到满意,所以这是我喜欢分享的问答帖子。

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

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