[译]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 ...
随机推荐
- sql server 2000 个人版怎么在win7下安装
win7 64位安装SQL2000个人版教程 首先,如果以前安装的话,要删除干净.我也找了半天的网络资料. 1.把原来sqlserver的安装目录 C:\Program Files\microsoft ...
- Python中Scrapy框架元素选择器XPath的简单实例
原文标题:<Python网络爬虫-Scrapy的选择器Xpath> 对原文有所修改和演绎 优势 XPath相较于CSS选择器,可以更方便的选取 没有id class name属性的标签 属 ...
- JavaScript深入之执行上下文栈
如果要问到 javascript 代码执行顺序的话,想必写过javascript的开发者都会有个直观的印象,那就是顺序执行,例如: var foo = function(){ console.log( ...
- [luogu4018][Roy&October之取石子]
题目链接 思路 这个题思路挺巧妙的. 情况一: 首先如果这堆石子的数量是1~5,那么肯定是先手赢.因为先手可以直接拿走这些石子.如果石子数量恰好是6,那么肯定是后手赢.因为先手无论怎样拿也无法直接拿走 ...
- 关于dp(背包)
有关背包,我这几天可是尽受其苦(不得不靠我聪颖的背诵代码的大脑来进行一波操作) Step 1 01背包 关于01背包的主要代码: ;j<=m;j++) { for(int i=n;i& ...
- python datetime 字符串 时间戳
#把datetime转成字符串 def datetime_toString(dt): return dt.strftime("%Y-%m-%d-%H") #把字符串转成dateti ...
- django基于存储在前端的token用户认证
一.前提 首先是这个代码基于前后端分离的API,我们用了django的framework模块,帮助我们快速的编写restful规则的接口 前端token原理: 把(token=加密后的字符串,key= ...
- Vuex速学篇:(2)利用state保存新闻数据
回顾 以前我们在做这个新闻列表的时候,是一个写死的数据 export default{ data(){ return{ newslist:[ {newsid:"101",pubti ...
- (数学) PTA 1005 继续(3n+1)猜想 (25 分)
1005 继续(3n+1)猜想 (25 分) 卡拉兹(Callatz)猜想已经在1001中给出了描述.在这个题目里,情况稍微有些复杂. 当我们验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程 ...
- java十进制转三十六进制
import java.util.HashMap; public class Ten2Thirty { private static final String X36 = "01234567 ...