[译]C#7 Pattern Matching
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之前,我们需要使用if和is语句去判断类别:
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表达式对值类型和引用类型都好使。
上面的例子中,变量s、c、r只有在模式匹配表达式为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的更多相关文章
- Beginning Scala study note(5) Pattern Matching
The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters ...
- Symbols of String Pattern Matching
Symbols of String Pattern Matching in Introduction to Algorithms. As it's important to be clear when ...
- scala pattern matching
scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中, ...
- Zhu-Takaoka Two-dimensional Pattern Matching
Two dimensional pattern matching. Details may be added later.... Corresponding more work can be foun ...
- [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 ...
- [Scala] Pattern Matching(模式匹配)
Scala中的match, 比起以往使用的switch-case有著更強大的功能, 1. 傳統方法 def toYesOrNo(choice: Int): String = choice match ...
- pattern matching is C# 7.0
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is 原来的版本 private static s ...
- C#9.0 终于来了,带你一起解读Pattern matching 和 nint 两大新特性玩法
一:背景 1. 讲故事 上一篇跟大家聊到了Target-typed new 和 Lambda discard parameters,看博客园和公号里的阅读量都达到了新高,甚是欣慰,不管大家对新特性是多 ...
- 函数式编程之-模式匹配(Pattern matching)
模式匹配在F#是非常普遍的,用来对某个值进行分支匹配或流程控制. 模式匹配的基本用法 模式匹配通过match...with表达式来完成,一个完整的模式表达式长下面的样子: match [somethi ...
随机推荐
- [APIO2016]烟火表演
题目描述 https://www.lydsy.com/JudgeOnline/problem.php?id=4585 题解 这题太神了. 我们可以先列出一个dp方程,dp[x][d]表示x节点到所有叶 ...
- Vue--的src文件
1.assest: 图片等等...... 2.components: 组件 3.App.vue: 根组件,三个部分:模板.行为(处理逻辑).样式: 模板: 只能有一个根标签: <HelloWor ...
- P1966 火柴排队
这道题需要小小的思考一波 (然而我思考了两节课) 好,我们先得出一个结论:a中第k大的与b中第k大的一定要排在一起,才能保证最小. 然后发现:挪a,b其实没有区别,故我们固定a,挪b. 然后我们就思考 ...
- 【洛谷P2568】GCD
题目大意:给定整数 \(N\),求\(1\le x,y\le N\) 且 \(gcd(x,y)\) 为素数的数对 \((x,y)\) 有多少对. 题解: \[ \sum_{p \in \text { ...
- bzoj3238 差异
题目链接 思路 观察题目中的式子,可以发现前两项是定值.所以只需要求出最后一项就行了. 然后题目就转化为了求字符串中所有后缀的\(lcp\)长度之和. 可以想到用后缀数组.在后缀数组上两个后缀的\(l ...
- 第三篇-以LinearLayout进行Android界面设计
一.新建一个项目 选择empty activity,此时项目里面没有main.java的文件. 二.手动创建java文件 Project那儿选择android模式,在app/java/com....一 ...
- Redis高并发和快速的原因
一.Redis的高并发和快速原因 1.redis是基于内存的,内存的读写速度非常快: 2.redis是单线程的,省去了很多上下文切换线程的时间: 3.redis使用多路复用技术,可以处理并发的连接 ...
- 蛋白质结构模型和功能预测:Swiss-model工具的使用
Swiss-model也是一款预测蛋白质结构模型的工具.网页地址:https://swissmodel.expasy.org/ 首先,进行常规的注册后,点击start modelling 以搜索BRC ...
- MySQL存储过程实现动态执行SQL
--存储过程名和参数,参数中in表示传入参数,out标示传出参数,inout表示传入传出参数 create procedure p_procedurecode(in sumdate varchar(1 ...
- sql>desc 存储包——查看包内存储过程、函数
sql>desc dbms_random: 查询dbms_random包下的存储过程和函数 a. value() 用于返回两个数值之间的随机数, value (low, high) SQL &g ...