如何将多个案例连接到switch语句中

时间:2014-10-31 13:50:10

标签: c# switch-statement

我有一个开关,我需要在相同的情况下做同样的程序。例如:

    enum Day
    {
        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
    }

    private string Do(Day day)
    {
        switch (day)
        {
            case Day.Monday:
                return "Study";
            case Day.Wednesday:
                return "Study";
            case Day.Friday:
                return "Study";
            case Day.Tuesday:
                return "Play Futbol";
            case Day.Thursday:
                return "Play Futbol";
            default: return "Party";
        }
    }

我喜欢加入案例陈述,我在那里做同样的程序。 我知道swith就像if-else语句一样,但是我想知道是否有任何方法可以通过切换来实现。

2 个答案:

答案 0 :(得分:3)

只需将您想要使用相同代码的案例放在一起。

正如格兰特在评论中指出的那样,它在文档中:http://msdn.microsoft.com/en-us/library/06tc147t.aspx

enum Day
{
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

private string Do(Day day)
{
    switch (day)
    {
        case Day.Monday:
        case Day.Wednesday:
        case Day.Friday:
            return "Study";
        case Day.Tuesday:
        case Day.Thursday:
            return "Play Futbol";
        default: 
            return "Party";
    }
}

答案 1 :(得分:2)

如果在多个案例中应该做同样的事情,你可以简单地堆叠这些案例:

private string Do(Day day)
{
    switch (day)
    {
        case Day.Monday:
        case Day.Wednesday:
        case Day.Friday:
            return "Study";
        case Day.Tuesday:
        case Day.Thursday:
            return "Play Futbol";
        default:
            return "Party";
    }
}

如果您需要在一个案例中执行某些操作然后再适用于另一个案例,则无法直接执行此操作。相反,你必须明确地写goto case

switch (str)
{
    case "1":
    case "small":
        cost += 25;
        break;
    case "2":
    case "medium":
        cost += 25;
        goto case "1";
    case "3":
    case "large":
        cost += 50;
        goto case "1";
    default:
        Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
        break;
}