Implementing pattern matching in C#

后端 未结 5 1869
耶瑟儿~
耶瑟儿~ 2021-02-04 03:54

In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

val title = content match {
    case blogPost: BlogP         


        
5条回答
  •  甜味超标
    2021-02-04 04:33

    Check out my pattern matching implementation: repo

    It's based on expressions, so it offers equal perfomance with nested ifs.

    Example usage:

    string s1 = "Hello";
    string s2 = null;
    
    Func> match = new Matcher>
    {
         {s => s is None, s => Console.WriteLine("None")},
         {s => s is Some, s => Console.WriteLine((string)s) // or s.Value
    };
    
    match(s1); // Hello
    match(s2); // None
    

    Available throught NuGet: Nuget package

提交回复
热议问题