输入consoleColor

时间:2017-01-17 22:14:20

标签: c# console-application

如何在c#console-application中获得consoleColor的输入?

我尝试了一些选项,但没有一个可以使用:

ConsoleColor c = ConsoleColor.parse(Console.ReadLine());
ConsoleColor c = Console.ReadLine();
ConsoleColor c = (ConsoleColor)Console.ReadLine();

2 个答案:

答案 0 :(得分:3)

Console.ReadLine()返回来自用户的字符串输入。 ConsoleColor是枚举。您需要解析输入字符串以获取枚举值:

ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), Console.ReadLine());

另请注意,用户可以输入控制台颜色名​​称不正确的值。在这种情况下,尝试解析输入会更好:

ConsoleColor color;
if (!Enum.TryParse(Console.ReadLine(), true, out color))
    Console.WriteLine("You have entered incorrect color name");

答案 1 :(得分:0)

获得这种颜色输入的一种相当方便的方法是通过整数值。用户总是希望输入最小值。因此,您可以使用基于整数/数字的菜单,该菜单对应于ConsoleColor枚举内部维护的枚举值,如下所示:

public enum ConsoleColor
    {
        //
        // Summary:
        //     The color black.
        Black = 0,
        //
        // Summary:
        //     The color dark blue.
        DarkBlue = 1,
        //
        // Summary:
        //     The color dark green.
        DarkGreen = 2,
        //
        // Summary:
        //     The color dark cyan (dark blue-green).
        DarkCyan = 3,
        //
        // Summary:
        //     The color dark red.
        DarkRed = 4,
        //
        // Summary:
        //     The color dark magenta (dark purplish-red).
        DarkMagenta = 5,
        //
        // Summary:
        //     The color dark yellow (ochre).
        DarkYellow = 6,
        //
        // Summary:
        //     The color gray.
        Gray = 7,
        //
        // Summary:
        //     The color dark gray.
        DarkGray = 8,
        //
        // Summary:
        //     The color blue.
        Blue = 9,
        //
        // Summary:
        //     The color green.
        Green = 10,
        //
        // Summary:
        //     The color cyan (blue-green).
        Cyan = 11,
        //
        // Summary:
        //     The color red.
        Red = 12,
        //
        // Summary:
        //     The color magenta (purplish-red).
        Magenta = 13,
        //
        // Summary:
        //     The color yellow.
        Yellow = 14,
        //
        // Summary:
        //     The color white.
        White = 15
    }

因此,在控制台上,您可以按类似的顺序向用户显示菜单:

Choose:
0 For Black
1 For DarkBlue
2 For DarkGreen
..and so on

现在只需从控制台读取整数输入并使用tryPparse API。 tryParse API同样有助于解析整数值并将其转换为枚举值:

var userInput = Console.ReadLine();//this will be an integer
ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor),userInput );
相关问题