当前位置:网站首页>C 11 new feature: List pattern matching

C 11 new feature: List pattern matching

2022-06-10 03:45:00 Dotnet cross platform

Before

Use pattern matching , You can test whether the expression result is equal to the specified constant or within a certain range :

public static string Demo(int number)
{
    return number switch
    {
        100 => "A",
        >=90 =>"B",
        _ => "C"
    };
}

The above code , The execution logic is as follows :

  • When the passed in variable is equal to 100, Return results A;

  • When the passed in variable is greater than or equal to 90, Return results B;

  • By default , Return results C;

however , Cannot pattern match array , For example, an element in an array is equal to 100, Return results A.

C# 11

from C# 11 Start , You can match an array or list to the pattern sequence of matching elements . Any of the following modes can be applied :

  • Check whether a single element matches certain characteristics

public static string Demo(int[] numbers)
{
    return numbers switch
    {
        [100] => "A",
        [>=90] => "B",
        _ => "C"
    };
}

Must exactly match the elements of the array , For example, the array has 2 Elements can only return results C.

  • Abandon the meta model (_) Match with a single element

[_, 100] => "A",
[>=90, _] => "B",

for example [90,100] Return results A,[90,80] Return results B.

  • Scope mode (..) You can match zero or more elements in a sequence . But at most one range mode in the list mode is allowed

[.., 100] => "A",
[>=90, ..] => "B",

for example [80,90,100] Return results A,[90] Return results B.

  • var Patterns can capture a single element or multiple elements

[var number, 100,.. var array] => $"{number},{string.Join(",",array)}",

for example [80,100] Return results 80,[80,100,70,60] Return results 80,70,60.

Decompile the list mode code , You can see , The code actually uses if-else Realized . List mode is just C# 11 A grammar sugar for us

0c45fc5b50f8765fa7b701b30c0a5dd4.png

Add microsignals 【MyIO666】, Invite you to join the technical exchange group

原网站

版权声明
本文为[Dotnet cross platform]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100334154856.html