首页 > 编程语言 >C#教程 - 模式匹配(Pattern matching)

C#教程 - 模式匹配(Pattern matching)

时间:2022-09-25 13:56:17浏览次数:48  
标签:obj C# Pattern int Season 匹配 Scheme true matching

更新记录
转载请注明出处:
2022年9月25日 发布。
2022年9月10日 从笔记迁移到博客。

常见匹配模式

类型匹配模式(type pattern)

属性匹配模式(property pattern)

匹配模式可以放在多种上下文中:

After the is operator (variable is pattern)

In switch statements

In switch expressions

类型匹配模式(type pattern)

实例:is类型匹配

if (obj is string s)
 Console.WriteLine (s.Length);

属性匹配模式(property pattern)

注意:从C# 7/8开始引入

实例:属性匹配

if (obj is string { Length:4 })
{
    //as same
    // if (obj is string s && s.Length == 4)
    Console.WriteLine ("A string with 4 characters");
}

实例:属性匹配

bool ShouldAllow (Uri uri) => uri switch
{
    { Scheme: "http", Port: 80 } => true,
    { Scheme: "https", Port: 443 } => true,
    { Scheme: "ftp", Port: 21 } => true,
    { IsLoopback: true } => true,
    _ => false
};

实例:

{ Scheme: string { Length: 4 }, Port: 80 } => true,
{ Scheme: "http", Port: 80 } when uri.Host.Length < 1000 => true,

实例:

bool ShouldAllow (object uri) => uri switch
{
    Uri { Scheme: "http", Port: 80 } => true,
    Uri { Scheme: "https", Port: 443 } => true,
}

元组匹配模式(Tuple Patterns)

注意:从C# 8开始支持

实例:

int AverageCelsiusTemperature (Season season, bool daytime) => (season, daytime) switch{
    (Season.Spring, true) => 20,
    (Season.Spring, false) => 16,
    (Season.Summer, true) => 27,
    (Season.Summer, false) => 22,
    (Season.Fall, true) => 18,
    (Season.Fall, false) => 12,
    (Season.Winter, true) => 10,
    (Season.Winter, false) => -2,
    _ => throw new Exception ("Unexpected combination")
};

位置匹配(Positional Patterns)

实例:

//测试使用的类型
class Point
{
    public readonly int X, Y;
    public Point (int x, int y) => (X, Y) = (x, y);
    //定义解构器
    public void Deconstruct (out int x, out int y)
    {
        x = X; y = Y;
    }
}
var p = new Point (2, 3);
//使用位置匹配模式
Console.WriteLine (p is (2, 3)); // true

//还可以在switch中使用位置匹配模式
string Print (object obj) => obj switch
{
    Point (0, 0) => "Empty point",
    Point (var x, var y) when x == y => "Diagonal"
    //...
};

var匹配(var Pattern)

注意:从C# 7开始支持

实例:

bool Test (int x, int y) =>
         x * y is var product && product > 10 && product < 100;

常量匹配(Constant Pattern)

可以将常量或字面量作为匹配

实例:

void Foo (object obj)
{
    // C# won't let you use the == operator, because obj is object.
    // However, we can use 'is'
    if (obj is 3) //...
    //as same
    //if (obj is int && (int)obj == 3) ...
}

标签:obj,C#,Pattern,int,Season,匹配,Scheme,true,matching
From: https://www.cnblogs.com/cqpanda/p/16718934.html

相关文章

  • 银河麒麟v10图形化完成DCA培训内容(基于达梦8)
    本文基于银河麒麟v10服务器版使用图像化方式完成DCA培训学习相关内容,如需命令行方式可观看上一篇:https://www.cnblogs.com/zdstudy/p/16726249.html安装数据库a.创建用......
  • win10下vscode链接wsl2
    win10下vscode链接wsl2其实之前一直对vscode有很不好的印象:比如编译正常但标红、json配置文件嘎嘎多难以上手;但是这一回被朋友推荐用它,拎出一个中午专门搞了下,感觉它的代......
  • static静态变量的理解
    静态变量类型说明符是static。静态变量属于静态存储方式,其存储空间为内存中的静态数据区(在静态存储区内分配存储单元),该区域中的数据在整个程序的运行期间一直占用这些存......
  • vue3 基础-自定义指令 directive
    上篇内容是关于mixin混入的一些操作,也是关于代码复用层面的,本篇讲自定义指令directive也是为了实现复用而设计的一些小功能啦.先来看看,如果不用directive的场......
  • Vue-router NavigationDuplicated 产生原因和解决方法
    当你的Vue项目在当前的路由下企图再次导航到当前路由时就会出现NavigationDuplicated的问题(通俗来讲就是多次进入了同一个path,比如说当前你在/user/user-list页面,这时候你......
  • cobbler的部署
    cobbler部署//配置yum源[root@localhost~]#curl-o/etc/yum.repos.d/CentOS-Base.repohttps://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo%Total%......
  • 规范你的 JSON 配置,试试 JSON schema
    不知道大家在写一些JSON配置时会不会经常觉得麻烦,每次都要打开文档去核对字段名称对不对、结尾有没有s、结构是否正确、是不是数组等问题。然而我最近发现一些开源项目......
  • Pytorch实现VAE
    变分自编码器Pytorch实现。1classVAE(nn.Module):2def__init__(self):3super(VAE,self).__init__()45self.fc1=nn.Linear(784,......
  • count(*), count(1), count(列名)的区别
    1.从结果上来看count(1)和count(*)之间没有区别,因为count(*)count(1)都不会去过滤空值,但count(列名)就有区别了,因为count(列名)会去过滤空值。2.从执行效率来看(1)如果列名为主键,count......
  • C语言第18天,字符串处理函数
    字符串处理函数与printf不同,这些函数不在之前熟悉的头文件stdio.h中。而是在字符串专用的头文件string.h中。1.获取字符串长度strlenstrlen函数可以获取字符数组中的字......