原文

public struct Square
{
public double Side { get; } public Square(double side)
{
Side = side;
}
}
public struct Circle
{
public double Radius { get; } public Circle(double radius)
{
Radius = radius;
}
}
public struct Rectangle
{
public double Length { get; }
public double Height { get; } public Rectangle(double length, double height)
{
Length = length;
Height = height;
}
}
public struct Triangle
{
public double Base { get; }
public double Height { get; } public Triangle(double @base, double height)
{
Base = @base;
Height = height;
}
}

下面分别使用7之前的语法和7来写一个计算形状面积的方法。

is 类型模式表达式

在C# 7.0之前,我们需要使用ifis语句去判断类别:

public static double ComputeArea(object shape)
{
if (shape is Square)
{
var s = (Square)shape;
return s.Side * s.Side;
}
else if (shape is Circle)
{
var c = (Circle)shape;
return c.Radius * c.Radius * Math.PI;
}
// elided
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}

在C# 7.0 中,通过使用is表达式的扩展可以在类型判断成功的时候将其分配给一个变量,从而简化上面的代码:

public static double ComputeAreaModernIs(object shape)
{
if (shape is Square s)
return s.Side * s.Side; // s 只在这可用
else if (shape is Circle c)
return c.Radius * c.Radius * Math.PI; // c 只在这可用
else if (shape is Rectangle r)
return r.Height * r.Length; // r 只在这可用
// elided
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}

新的is表达式对值类型和引用类型都好使。

上面的例子中,变量scr只有在模式匹配表达式为true的时候才作用被分配。

通过switch语句使用模式匹配

之前switch只支持常量模式。只能将变量和case中的常量进行比较:

public static string GenerateMessage(params string[] parts)
{
switch (parts.Length)
{
case 0:
return "No elements to the input";
case 1:
return $"One element: {parts[0]}";
case 2:
return $"Two elements: {parts[0]}, {parts[1]}";
default:
return $"Many elements. Too many to write";
}
}

7之前switch只支持常量模式。在C# 7.0 中没有这个限制了,可以通过switch来使用类型模式:

public static double ComputeAreaModernSwitch(object shape)
{
switch (shape)
{
case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
case Rectangle r:
return r.Height * r.Length;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}

case表达式中使用when

public static double ComputeArea_Version3(object shape)
{
switch (shape)
{
case Square s when s.Side == 0:
case Circle c when c.Radius == 0:
return 0; case Square s:
return s.Side * s.Side;
case Circle c:
return c.Radius * c.Radius * Math.PI;
default:
throw new ArgumentException(
message: "shape is not a recognized shape",
paramName: nameof(shape));
}
}

case表达式中声明变量

static object CreateShape(string shapeDescription)
{
switch (shapeDescription)
{
case "circle":
return new Circle(2); case "square":
return new Square(4); case "large-circle":
return new Circle(12); case var o when (o?.Trim()?.Length ?? 0) == 0:
// white space
return null;
default:
return "invalid shape description";
}
}

[译]C#7 Pattern Matching的更多相关文章

  1. Beginning Scala study note(5) Pattern Matching

    The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters ...

  2. Symbols of String Pattern Matching

    Symbols of String Pattern Matching in Introduction to Algorithms. As it's important to be clear when ...

  3. scala pattern matching

    scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中, ...

  4. Zhu-Takaoka Two-dimensional Pattern Matching

    Two dimensional pattern matching. Details may be added later.... Corresponding more work can be foun ...

  5. [PureScript] Break up Expressions into Cases in PureScript using Simple Pattern Matching

    Pattern matching in functional programming languages is a way to break up expressions into individua ...

  6. [Scala] Pattern Matching(模式匹配)

    Scala中的match, 比起以往使用的switch-case有著更強大的功能, 1. 傳統方法 def toYesOrNo(choice: Int): String = choice match ...

  7. pattern matching is C# 7.0

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is 原来的版本 private static s ...

  8. C#9.0 终于来了,带你一起解读Pattern matching 和 nint 两大新特性玩法

    一:背景 1. 讲故事 上一篇跟大家聊到了Target-typed new 和 Lambda discard parameters,看博客园和公号里的阅读量都达到了新高,甚是欣慰,不管大家对新特性是多 ...

  9. 函数式编程之-模式匹配(Pattern matching)

    模式匹配在F#是非常普遍的,用来对某个值进行分支匹配或流程控制. 模式匹配的基本用法 模式匹配通过match...with表达式来完成,一个完整的模式表达式长下面的样子: match [somethi ...

随机推荐

  1. layer 弹出层

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. 20165223 结对编程之四则运算week1-阶段性总结

    目录 一.结对对象 二.需求分析 三.设计思路 四.功能截图 五.结对感受 一.结对对象 担任角色 驾驶员(Driver):20165223 蔡霓(是控制键盘输入的人) 领航员(Navigator): ...

  3. Python 分布式进程

    #-*-coding:utf-8-*- '''分布式进程指的是将Process进程分不到多台机器上,充分利用多台机器的性能完成复杂的任务''' #服务器端 #--------------------- ...

  4. Python学习day4 数据类型Ⅱ(列表,元祖)

    day4 知识补充&数据类型:列表,元祖 1.知识补充 1.编译型/解释型 编译型:在代码编写完成之后编译器将其变成另外一个文件教给你算计执行. 代表语言:Java,c,c++ ,c#, Go ...

  5. [luogu4556][Vani有约会]

    题目链接 吐槽 这道题调了7个小时也是够了.最后只好比着题解做了一遍2333 思路 首先考虑n=2000的情况.因为这是在一条路径上,所以可以考虑差分.用a[i][j]表示第i个点中j这种粮食出现的次 ...

  6. 网上找的Backbone.js

    // Backbone.js 0.9.2 // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely ...

  7. maven+testng+eclipse

    1.安装maven 2.安装testng 3.配置maven的dependency,和build <project xmlns="http://maven.apache.org/POM ...

  8. (链表) leetcode 328. Odd Even Linked List

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note her ...

  9. MySQL_函数(待续)

    1.REPLACE(str,from_str,to_str) 定义:REPLACE(str,from_str,to_str) 解释:返回值是把字符串str 中的子串from_str 全部替换为to_s ...

  10. Java Web之JSP

    什么是JSP? JSP就是一个可以写Java代码的HTML页面 JSP是什么? JSP是Servlet,JSP的本质就是Servlet Tomcat的web.xml文件下有这样几段代码: 看到下面的通 ...