如何在 C# 中将颜色作为参数传递?

How to pass color as parameter in c#?

我需要在控制台应用程序中多次更改字体颜色。 而不是每次键入(或复制): Console.ForegroundColor = ConsoleColor.MyColor; 在我的代码中, 我只想打字 c(Red)c(Yellow)。 我想过这样的事情:

static void c(<???> myColor){
   Console.ForegroundColor = ConsoleColor.MyColor;
}

我怎样才能做到这一点?

而不是传递 c(Red) 传递 c(ConsoleColor.Red) 并在方法 c()

的定义中使用 ConsoleColor 枚举类型的参数
public static void c(ConsoleColor myColor){
   Console.ForegroundColor = myColor;
} 

调用函数使用

c(ConsoleColor.Red);

MSDN ConsoleColor


I want to type only c(Red) or c(Yellow)

如果你想传递名为 RedYellow 的字符串并将 ForegroundColor 分配给你的控制台,那么你可以尝试下面的方法

public static void SetForegroundColor(string colorName)
{
   //Set black as foreground color if TryParse fails to parse color string. 
   if(Enum.TryParse(ConsoleColor, colorName, out ConsoleColor color)
       Console.ForegroundColor = color;
   else
       Console.ForegroundColor = ConsoleColor.Black;

}

现在您可以将颜色名称作为字符串传递给此函数,喜欢

SetForegroundColor("Red");
SetForegroundColor("Yello");

MSDN: Enum.TryPrase

您可以使用以下方法设置控制台的前景色。我将该函数命名为 SetConsoleForeground 但您可以随意设置它,例如 c

/// <summary>
/// Sets Console Foreground color to the given color
/// </summary>
/// <param name="consoleColor">Foreground color to set</param>
private static void SetConsoleForeground Color(ConsoleColor consoleColor) {
    Console.ForegroundColor = consoleColor;
}