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

how do i use an array in a switch statement in c#?

所以我是编程新手,所以我对此很困惑。我创建了一个数组并尝试在 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;
        }
}

据我所知,这没有问题。但是,当我 运行 代码时,我遇到了这个错误:"A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type"

我真的被这个问题困住了,我无法在互联网上找到任何答案,所以任何帮助将不胜感激。谢谢

您正在对整个数组执行 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
    }
}

听起来您要找的是 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;
}

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 语句中使用。