开发者

Use an object's string.contains method within a switch statement?

Basically something along the lines of:

switch (string.contains(x))
{
    case(x = "asdf"):
        break;
    case(x = "jkl"):
        break;
    case(x = "qwerty"):
        br开发者_StackOverflow中文版eak;
}

edit: Sorry guys, what I'd ideally like is to have the switch statement check the string for several different values, and depending on which of the values it finds inside the string, execute the appropriate code.


You can't do this unfortunately, however you can apply "functional pattern matching". Read up here on how to do it:

http://codebetter.com/matthewpodwysocki/2008/09/16/functional-c-pattern-matching/


You mean this, as far as I could figure it out:

if (string.Contains(x))
{
    switch (x)
    {
        case "asdf":
            break;
        case "jkl":
            break;
        case "qwerty":
            break;
    }
}


The Contains(string s) method returns a boolean, so it is not permissible in the switch statement.


The switch keyword has some magic (a lookup table), since it can never throw an exception.

You can rewrite it just as succinctly as:

if (x.Contains("asdf"))
{}
else if (x.Contains("jkl"))
{}
else if (x.Contains("qwerty"))
{}


Have you tried this:

    switch (true)
    {
        case string.Contains("asdf"):
            break;
        case string.Contains("jkl"):
            break;
        case string.Contains("qwerty"):
            break;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜