为我想要的任何颜色编写代码的方法

时间:2018-08-01 16:26:48

标签: c#

public static void TextColor(string green, string blue, string red)
{
    green = Console.ForegroundColor = ConsoleColor.Green;
    blue = Console.ForegroundColor = ConsoleColor.Blue;
    red = Console.ForegroundColor = ConsoleColor.Red;
}

我得到的错误是:

  

不能将类型'System.ConsoleColor'隐式转换为'string'

我正在尝试创建一个这样的方法:TextColor(Green),基本上,这将要做:Console.ForegroundColor = ConsoleColor.Green,显然我想对所有颜色都这样做,然后调用任何一种颜色我想要(只是节省时间,所以我不必每次都输入:Console.ForegroundColor = ConsoleColor.[specific color])。

1 个答案:

答案 0 :(得分:2)

如果您的参数是字符串,则可以解析值:

public static void TextColor(string colorString)
{
  Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorString);
}

示例:

TextColor("Green"); // Sets Console.ForegroundColor to ConsoleColor.Green
TextColor("Blue"); // Sets Console.ForegroundColor to ConsoleColor.Blue