How to handle multiple values inside one case?

How to handle multiple values inside one case ? So if I want to execute the same action for value "first option" and "second option" ?

Is this the right way?

switch(text)
{
    case "first option":
    {
    }
    case "second option":
    {
        string a="first or Second";
        break;
    }
}

It's called 'multiple labels' in the documentation, which can be found in the C# documentation on MSDN.

A switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below). However, no two case labels may contain the same constant value.

Your altered code:

string a = null;

switch(text)
{
    case "first option":
    case "second option":
    {
        a = "first or Second";
        break;
    }
}

Note that I pulled the string a out since else your a will only be available inside the switch .


有可能的

switch(i)
                {
                    case 4:
                    case 5:
                    case 6: 
                        {
                            //do someting
                            break; 
                        }
                }

如果您希望能够将两者一起对待并将其作为独立案例分开, if最好使用if语句:

if (first && second)
{
    Console.WriteLine("first and second");
}
else if (first)
{
    Console.WriteLine("first only");
}
else if (second)
{
    Console.WriteLine("second only");
}
链接地址: http://www.djcxy.com/p/84456.html

上一篇: 开关中错误的多个案例不会产生编译器错误

下一篇: 如何处理一个案件中的多个值?