Pattern Matching on a string

走远了吗. 提交于 2019-12-10 14:36:44

问题


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?


回答1:


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;
}

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



来源:https://stackoverflow.com/questions/42952535/pattern-matching-on-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!