Practice Pattern Matching in C #6,
Pattern Matching is a very useful language feature in F. It is estimated that many people want to use this feature in C.
In one sentence, pattern matching is: creating a function can accept and process expressions of different types (including different parameters and types ). For example, if you write a function named format, you can process variables, constants, addition, and multiplication in the expression "x hour (1 + 2.
Tomas Petricek complained about the shortcomings of C # in this aspect in his blog "Pattern matching in action using C #6, then I also figured out that although C #6 provides the pattern matching capability, Microsoft would not have to hide it for everyone.
In addition to complaints, he also introduced how to implement model matching in C # And C.
Since C # Is a typed programming language, you cannot write discriminated union types ). Interestingly, F # regards exceptions as a classless union type. In turn, we can use exceptions in C # To implement model matching, that is: use the expression as a parameter of the Exception type, throw the expression, and then use catch to match the expression.
Based on this idea, C # can implement the similar pattern matching function to calculate the mathematical expression "x round (1 + 2.
If the new feature of exception filters in C # is used, it is easier to calculate mathematical expressions through pattern matching. (Tomas says that Microsoft hides and holds that the exception filter is actually a pattern matching)
Address: http://tomasp.net/blog/2015/csharp-pattern-matching/index.html