令人困惑的开关/案例结果

BBi*_*ell -1 c# switch-statement

当然在发布此错误之前我搜索了它.下面的代码返回:错误CS0029:无法在两个位置隐式地将类型'bool'转换为'string'.我误解为什么下面的代码没有返回字符串?想一想Stack Overflow可能会给出什么建议我已经尽力明确地转换为字符串,但只是设法让自己感到困惑.

public static class Bob
{
    public static string Response(string statement)
    {
        string teststring = statement;

        bool IsAllUpper(string input)
        {
            for (int i = 0; i < input.Length; i++)
            {
                if (Char.IsLetter(input[i]) && !Char.IsUpper(input[i]))
                    return false;
            }
            return true;
        }

        switch(teststring)
        {
        case IsAllUpper(teststring) && teststring.EndsWith("?"):
            string final1 = "Calm down, I know what I'm doing!";
            return final1;   

        case teststring.EndsWith("?"):
            string final2 = "Sure";
            return final2;

        default:
            string final3 = "Whatever.";
            return final3;
        }
    }

    public static void Main()
    {
        string input = "This is the end";
        Console.WriteLine("{0}", Response(input));
    }
}
Run Code Online (Sandbox Code Playgroud)

Glo*_*del 5

随着switch(teststring)你问的代码在切换字符串值,如"富"与"酒吧".但是,你的cases是布尔值:IsAllUpper(teststring)并且teststring.EndsWith("?")都返回布尔值.

考虑用if语句替换switch块,例如

if (IsAllUpper(teststring) && teststring.EndsWith("?")) {
    string final1 = "Calm down, I know what I'm doing!";
    return final1;
}   

if (teststring.EndsWith("?")) {
    string final2 = "Sure";
    return final2;
}

string final3 = "Whatever.";
return final3;
Run Code Online (Sandbox Code Playgroud)

或者,为了最大限度地简明扼要,单行:

return teststring.EndsWith("?") ? (IsAllUpper(teststring) ? "Calm down, I know what I'm doing!" : "Sure") : "Whatever."
Run Code Online (Sandbox Code Playgroud)