3

无法在 switch 语句中添加多个条件。如何使用 switch 语句来做到这一点?我必须使用多个 if 条件吗?

string oldValue = ".....long string1....";
string newValue = ".....long string2....";
switch (oldValue.Length && newValue.Length)
{
    case <500 && <500:
        //insert as is
        break;
    case >500 && <500:
        //split oldValue into array of strings and insert each
        //insert newValue as is
        break;
    case <500 && >500:
        //insert oldValue As is
        //split newValue into array of strings and insert each
        break;
    case >500 && >500:
        //split oldValue into array of strings and insert each
        //split newValue into array of strings and insert each
        break;
    default:
        break;
}
4

4 回答 4

5

不,你不能这样做。switch语句测试值,而不是表达式。

您需要改用if语句。

于 2012-10-18T07:57:09.613 回答
3

查看您的评论, 的长度oldValue仅影响您使用的内容oldValue,而 的长度newValue仅影响您使用的内容newValue

为什么不把它分成两个单独的语句?甚至变成通用方法?

string[] GetValuesToInsert(String input)
{
    if (input.Length < 500)
        return new[] {input};
    else
        return input.Split(...);
}

whatever.Insert(GetValuesToInsert(oldValue));
whatever.Insert(GetValuesToInsert(newValue));
于 2012-10-18T08:00:01.287 回答
1

你不能这样做,你需要使用ifand else if

switch通常使用不同的技术来跳转到正确的分支(称为 jumptable)。基本上它是一个单跳,其目标位置是从 of 中计算出来的valueswitch(value)而不是许多顺序比较。细节取决于架构。

于 2012-10-18T07:57:37.800 回答
0

只是你打破了 switch 语句规则。你不能在那里传递表达式。您需要传递一个值。请参考以下链接 http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx

您需要使用 if-else 语句。

于 2012-10-18T08:00:38.880 回答