c# - 如何使用变量完成指令?

标签 c# .net

我想制作一个函数,在调用时使用我选择的颜色更改控制台的颜色。我不想每次都写 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.BackgroundConsoleColor.Foreground 我想换成 ConsoleColor.DarkCyanConsoleColor.White,正如我在 WindowColor("DarkCyan","White"); 中调用的那样。

但是我得到这个错误:

'ConsoleColor' does not contain a definition for 'Background'.

现在我知道 ConsoleColor.Background 中的 Background 不被视为变量,而是指令的一部分,但问题是:如何我可以让 BackgroundForeground 以变量的形式被视为指令的完成吗?

最佳答案

通常,您只需使用正确类型的参数而不是字符串:

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/

相关文章:

c# - 可以在 c#.net 控制台中暂停、缓存、刷新键盘输入吗?

c# - float 学,63.500000 x 2 = 127000000

c# - 如何获取 Windows 应用商店应用程序的本地化显示名称

c# - Assembly.GetCustomAttributes 仍然被认为是最佳方法吗?

.net - 在 WPF 中检测鼠标下的子控件

c# - 如何从统一容器中按名称获取类型的所有实例?

c# - 从 C# process.StandardOutput.ReadLine() 运行命令行挂起

C# Opengl Hook Swapbuffer 添加插值帧

c# - 不知何故MySQL在运行后突然无法执行查询

c# - 我可以有一个方法的扩展方法吗?