如何在 switch case 中使用枚举来比较字符串-C#

vmb*_*vmb 0 .net c# enums

我有一个像下面这样的枚举

public enum Colors
{
    red,
    blue,
    green,
    yellow
}
Run Code Online (Sandbox Code Playgroud)

我想用它开关盒

public void ColorInfo(string colorName)
{
    switch (colorName)
    {
        // i need a checking like (colorname=="red")
        case Colors.red:
            Console.log("red color");
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

 Cannot implicitly convert type 'Color' to string
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助解决这个问题..

Mic*_*iey 5

在我看来,您最好的选择是尝试将string作为输入获得的值解析为Colors值,然后您可以switch仅根据枚举进行操作。您可以通过使用以下Enum.TryParse<TEnum>功能来做到这一点:

public void ColorInfo(string colorName)
{
    Colors tryParseResult;
    if (Enum.TryParse<Colors>(colorName, out tryParseResult))
    {
        // the string value could be parsed into a valid Colors value
        switch (tryParseResult)
        {
            // i need a checking like (colorname=="red")
            case Colors.red:
                Console.log("red color");
                break;
        }
    }
    else
    {
        // the string value you got is not a valid enum value
        // handle as needed
    }
}
Run Code Online (Sandbox Code Playgroud)