原文

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. luogu1397 [NOI2013]矩阵游戏 (等比数列求和)

    一个比较显然的等比数列求和,但有一点问题就是n和m巨大.. 考虑到他们是在幂次上出现,所以可以模上P-1(费马小定理) 但是a或c等于1的时候,不能用等比数列求和公式,这时候就要乘n和m,又要变成模P ...

  2. Billiard CFR484 div2 (数论)

    就是一个点从开始的点在一个矩形内往某个方向一直运动,如果碰到了矩形的边,那么就反弹,我们可以把这个矩形拓展开,那么就是问题变成了我有没有一个点,这个点的坐标(Tx, Ty)满足n|Tx,m|Ty 那么 ...

  3. nginx+腾讯云免费ssl证书+阿里云ECS实现Https配置

    1. 申请SSL证书: 首先我们需要到腾讯云那边申请一个ssl证书,对于个人博客类型的,建议采用免费版本,土豪除外 申请地址:https://console.cloud.tencent.com/ssl ...

  4. Java 破解谷歌翻译api,可以实现程序自动化翻译文章

    1  原理:查看谷歌翻译网站,输入需要翻译的文字,选择语言得到翻译后的文字,发送异步请求参数返回结果.java使用httpclient发送请求,实现使用代码翻译文章的功能. 2  下载代码后,测试入口 ...

  5. 在 Docker 中使用 mysql 的一些技巧

    启动到后台:  docker-compose start docker-composer 执行命令: entrypoint: pwd app: build: ./app working_dir: /a ...

  6. (转)java中引用传递和值传递

    https://blog.csdn.net/javazejian/article/details/51192130 https://www.cnblogs.com/perfy/archive/2012 ...

  7. java web session过期 跳转页面没有跳出frame的问题

    对于frame页面框架的java web项目,如果session过期执行跳转操作时,只在一个frame中(例如center frame)跳转到设置的login页面了,为了能直接跳转到最初的登录页面,就 ...

  8. 【译】8. Java反射——注解

    原文地址:http://tutorials.jenkov.com/java-reflection/annotations.html ================================== ...

  9. TestNg 7.依赖测试

    我本个测试方法执行的时候,依赖于其他的方法.用到关键字dependsOnmethods(依赖于那个方法)也有依赖于哪个组(dependsOnGroups). 看以下的一段代码: package com ...

  10. post请求中data参数的应用

    一.data为参数,json是自动的把参数转换成了json格式,一般建议用json ,url是请求地址. 二,以一个网站来做解释,看登陆的请求 抓包看一下: 用在代码里面看一下: 如果不转的话,那么用 ...