字符串上的模式匹配 [英] Pattern Matching on a string

查看:54
本文介绍了字符串上的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法在 c# 7 中做这样的事情

I was wondering if there is a way to do something like this in c# 7

        var test = "aaeag";
        switch (test)
        {
            case test.StartsWith("a"):
                break;
            default:
                break;
        }

遗憾的是,这看起来不太可能.这是正确的还是我做错了什么?

Sadly it does not look like it possible. Is this correct or am I doing something wrong?

推荐答案

这在 C# 7 中是可能的,使用 when 保护:

This is possible with C# 7, using a when guard:

var test = "aaeag";
switch (test)
{
    case var s when s.StartsWith("a"):
        break;
    default:
        break;
}

您的代码版本正在做什么通常被称为活动模式.通过例如定义扩展方法:

What your version of the code is doing is often referred to as active patterns. By eg defining the the extension method:

public static bool StartsWithPattern(this string str, string matchPattern) => 
    str.StartsWith(matchPattern);

那么你的开关可能会变成:

Then your switch could become:

var test = "aaeag";
switch (test)
{
    case StartsWith("a"):
        break;
    default:
        break;
}

如果您希望在未来的 C# 版本中看到此功能,请赞成此提案.

If you'd like to see this feature in a future C# version, then please upvote this proposal.

这篇关于字符串上的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆