比较 switch-case 块中具有不同大小写的 C# 字符串

use*_*596 3 c# asp.net

我有一组 switch-case 语句,例如“你好,你好吗”,“嗨,我能为你做什么?”。如果用户的输入是逐字输入,即:“Hello, how are you”,则匹配有效。

但如果用户输入“Hello, How are You”,则匹配失败。

我希望如果用户的输入相同但大小写不同,那么它应该匹配。IE

"Hello, how are you" == "Hello, How are You" == "HELLO, how are YOU"
Run Code Online (Sandbox Code Playgroud)

如何才能做到这一点?

Kar*_*ran 6

如果您正在使用C# 7.0或更新版本,则可以使用如下Pattern Matching所示switch..case

string a = "Hello, How are You";

switch (a)
{
    case string str when str.Equals("hello, how are you", StringComparison.InvariantCultureIgnoreCase):
        // Your code
        break;
    default:
        // default code
        break;

}
Run Code Online (Sandbox Code Playgroud)