我如何在c#的switch语句中使用数组?

时间:2015-07-06 19:47:32

标签: c# arrays switch-statement

所以我是编程的新手,所以我对此非常困惑。我创建了一个数组并尝试在switch语句中使用它:

string[] General = new string[5];
{
    General[0] = "help";
    General[1] = "commands";
    General[2] = "hello";
    General[3] = "info";
    General[4] = "quit";
}

switch(General)
{
    case 0:
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
            Console.ForegroundColor = oldColor;
            continue;
        }
}

据我所知,这没有问题。但是,当我运行代码时,我遇到了这个错误:"开关表达式或案例标签必须是bool,char,string,integral,enum或相应的可空类型"

我真的坚持这个,我无法在互联网上找到任何答案,所以任何帮助将不胜感激。谢谢

3 个答案:

答案 0 :(得分:1)

您正在整个阵列上执行switch语句,而不是数组中的单个条目。

假设您正在尝试编写所有可用的输入

    string[] General = new string[5];
    {
        General[0] = "help";
        General[1] = "commands";
        General[2] = "hello";
        General[3] = "info";
        General[4] = "quit";
    }

foreach(var option in General)
{
    switch(option)
    {
        case "help":
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
                Console.ForegroundColor = oldColor;
                break;
            }
        case "commands":
            {
                //Do some stuff
                break;
            }
        //etc etc
    }
}

答案 1 :(得分:1)

听起来你正在寻找的是enum

public enum General {
    help = 0,
    commands = 1,
    hello = 2,
    info = 3,
    quit = 4
}

然后你就可以使用switch语句了。)。

// variable to switch
General myGeneral;

// myGeneral is set to something

switch(myGeneral)
{
    case General.help:
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine("This is a new program. Therefore the amount of commands are limited. \nIt can do simple things. For example, if you say 'tell the time' then it will tell the time\n");
        Console.ForegroundColor = oldColor;
        break;
}

答案 2 :(得分:0)

switch语句中的参数应该是用户输入,而不是您的可选值,例如:

int input = 0; // get the user input somehow
switch (input)
{
    case 0: 
    {
        // Do stuff, and remember to return or break
    }
    // Other cases
}

此外,这是Enum的完美用例。这看起来像这样:

public enum General 
{
    HELP = 0,
    COMMANDS = 1,
    HELLO = 2,
    INFO = 3,
    QUIT = 4
}

int input = 0; // get the user input somehow
switch (input)
{
    case General.HELP: //Notice the difference?
    { 
        // Do stuff, and remember to return or break
    }
    // Other cases
}

这使您的意图非常清晰,因此使您的代码更具可读性和可维护性。您不能对您的数组执行此操作,因为即使您在代码中声明了数组,它仍然是可变的,因此在编译时不知道它在switch语句中的状态。 Enum是不可变的,因此它们的值在编译时是已知的,可以在switch语句中使用。