C#教程 - 模式匹配(Pattern 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) ...
}

作者:重庆熊猫

出处:https://www.cnblogs.com/cqpanda/p/16718934.html

版权:本作品采用「不论是否商业使用都不允许转载,否则按3元1字进行收取费用」许可协议进行许可。

posted @   重庆熊猫  阅读(469)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示