Implementing pattern matching in C#

后端 未结 5 1738
耶瑟儿~
耶瑟儿~ 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:26

    Pattern matching is one of those lovely features mostly found in functional programming languages like F#. There is a great project going on in codeplex named Functional C#. Consider the following F# code:

    let operator x = match x with
                     | ExpressionType.Add -> "+"
    
    let rec toString exp = match exp with
                           | LambdaExpression(args, body) -> toString(body)
                           | ParameterExpression(name) -> name
                           | BinaryExpression(op,l,r) -> sprintf "%s %s %s" (toString l) (operator op) (toString r)
    

    Using the Functional C# library, the C# equivalent would be:

    var Op = new Dictionary { { ExpressionType.Add, "+" } };
    
    Expression> add = (x,y) => x + y;
    
    Func toString = null;
     toString = exp =>
     exp.Match()
        .With(l => toString(l.Body))
        .With(p => p.Name)
        .With(b => String.Format("{0} {1} {2}", toString(b.Left), Op[b.NodeType], toString(b.Right)))
        .Return();
    

提交回复
热议问题