原文

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. 【linux】硬盘原理简介和分区

    硬盘是计算机重要的一个部件,计算机中的数据都是保存在硬盘中,比如mysql的数据,linux系统日志及其他的应用日志,还有很多视频,音频,图片等文件都是保存在硬盘中,所以硬盘是计算机不可或缺的一个部件 ...

  2. kafka清理数据日志

    背景问题: 使用kafka的路上踩过不少坑,其中一个就是在测试环境使用kafka一阵子以后,发现其日志目录变的很大,占了磁盘很大空间,定位到指定目录下发现其中一个系统自动创建的 topic,__con ...

  3. centos7破解安装confluence5.9.11

    应用环境:Confluence是一个专业的企业知识管理与协同软件,也可以用于构建企业wiki.通过它可以实现团队成员之间的协作和知识共享. 安装环境:centos7.3 Java环境 1.7.0_79 ...

  4. 在linux环境下搭建JDK+JAVA+Mysql,并完成jforum的安装

    参考链接: YUM安装MySQL和JDK和Tomcat:http://cmdschool.blog.51cto.com/2420395/1696206/ http://www.cnblogs.com/ ...

  5. Apache Beam实战指南 | 手把手教你玩转KafkaIO与Flink

    https://mp.weixin.qq.com/s?__biz=MzU1NDA4NjU2MA==&mid=2247492538&idx=2&sn=9a2bd9fe2d7fd6 ...

  6. “adb不是内部或外部命令,也不是可运行的程序或批量文件“

    首先这个问题有两种可能: 1.就是没有配置环境变量, 这个只需要将android安装:例如C:\Program File\android-sdk-windows\tools加入到 系统变量Path中, ...

  7. appium-基础搭建,适配,问题,优化,提速

    搭建开发环境,导入testng/log4j/maven 1.配置jdk环境 2.安装appium,下载eclipse-adt,配置appium环境 github.com/getlantern/foru ...

  8. java equals和hashcode方法

    equals()方法比较两个对象的引用是否相同 hashcode()方法比较两个对象的哈希码是否相同

  9. 打印流(PrintWriter )

    PrintWriter package cn.lijun.demo1; import java.io.File; import java.io.FileNotFoundException; impor ...

  10. Yii2的mongodb的聚合操作

    最近项目使用到mongodb的聚合操作,但是yii文档中对这方面资料较少,记录下 $where['created_time'] = ['$gt' => "$start_date_str ...