原文

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. Baker Vai LightOJ - 1071 (MCMF)

    在个给出的矩阵从,从左上角走到右下角,然后再从右下角走到左上角,两次不能经过想同的点,每个点都有一个价值,问最大的价值是多少. 可以把原来的问题化简成从左上角走两条路到右下角,然后把价值加起来,然是这 ...

  2. zxing二维码的生成与解码(C#)

    ZXing是一个开源Java类库用于解析多种格式的1D/2D条形码.目标是能够对QR编码.Data Matrix.UPC的1D条形码进行解码. 其提供了多种平台下的客户端包括:J2ME.J2SE和An ...

  3. Django(十一)请求生命周期之响应内容(请求/响应 头/体)

    https://www.cnblogs.com/renpingsheng/p/7534897.html Django请求生命周期之响应内容 http提交数据的方式有"post",& ...

  4. 扩展方法、委托和Lambda

    举例演化Lambda string[] names ={"Burke", "Connor", "Frank", "Everett& ...

  5. BeautifulSoup获取图片

    参看文档:https://www.cnblogs.com/forever-snow/p/8506746.html

  6. halcon图像处理的基本思路

    原图素材,1.jpg 过程图: 结果图: 代码及注意事项: read_image (Image, 'C:/Users/Jv/Desktop/1.jpg') rgb1_to_gray (Image, G ...

  7. (栈)leetcode496. Next Greater Element I

    You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of n ...

  8. (栈 注意格式)P1739 表达式括号匹配 洛谷

    题目描述 假设一个表达式有英文字母(小写).运算符(+,—,*,/)和左右小(圆)括号构成,以“@”作为表达式的结束符.请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“YES”:否则返 ...

  9. Vue(基础六)_嵌套路由(续)

    一.前言                  1.路由嵌套里面的公共路由                  2.keep-alive路由缓存                  3.导航守卫 二.主要内容 ...

  10. opencv: 排序

    opencv提供了排序函数:  sort和sorIdx , 其中sortIdx可以获取排序后的序号,比较方便: sortIdx原型: C++: void sortIdx(InputArray src, ...