我想制作一个函数,在调用时使用我选择的颜色更改控制台的颜色。我不想每次都写 3 条指令,所以这就是为什么我希望它在一个函数中。
到目前为止,我已经做了类似的事情:
public static void WindowColor(string Background, string Foreground)
{
Console.BackgroundColor = ConsoleColor.Background;
Console.ForegroundColor = ConsoleColor.Foreground;
Console.Clear();
}
static void Main(string[] args)
{
WindowColor("DarkCyan","White");
}
其中 ConsoleColor.Background
和 ConsoleColor.Foreground
我想换成 ConsoleColor.DarkCyan
和 ConsoleColor.White
,正如我在 WindowColor("DarkCyan","White");
中调用的那样。
但是我得到这个错误:
'ConsoleColor' does not contain a definition for 'Background'.
现在我知道 ConsoleColor.Background
中的 Background
不被视为变量,而是指令的一部分,但问题是:如何我可以让 Background
或 Foreground
以变量的形式被视为指令的完成吗?
最佳答案
通常,您只需使用正确类型的参数而不是字符串:
public static void WindowColor(ConsoleColor background, ConsoleColor foreground)
{
Console.BackgroundColor = background;
Console.ForegroundColor = foreground;
Console.Clear();
}
static void Main(string[] args)
{
WindowColor(ConsoleColor.DarkCyan, ConsoleColor.White);
}
如果你坚持将字符串作为参数,你将不得不解析它们:
public static void WindowColor(string Background, string Foreground)
{
Console.BackgroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), Background, true);
Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), Foreground, true);
Console.Clear();
}
static void Main(string[] args)
{
WindowColor("DarkCyan","White");
}
关于c# - 如何使用变量完成指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936400/