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

本文关键字:数组 语句 switch | 更新日期: 2023-09-27 18:01:20

所以我是新的编程,所以我很困惑这个。我创建了一个数组,并试图在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, integer, enum或相应的可空类型"

我真的被这个困住了,我在网上找不到任何答案,所以任何帮助都会非常感激。由于

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

听起来你要找的是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语句,而不是对数组中的单个条目执行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
    }
}

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