C# 使用字符串更改foregroundcolor和背景色

C# 使用字符串更改foregroundcolor和背景色,c#,C#,我试图用一个字符串来改变背景和前景的颜色 Console.Write("Color:"); string backgroundcolor = Convert.Tostring(Console.ReadLine()); 然后背景色变为我写的那种控制台前景/背景色可以通过属性设置 可用的颜色选项在枚举中定义 我们可以使用从字符串值以编程方式设置这些值 下面是一个快速示例程序,它将根据用户的输入设置Console.ForgroundColor和Console.BackgroundColor(如果指定

我试图用一个字符串来改变背景和前景的颜色

Console.Write("Color:");
string backgroundcolor = Convert.Tostring(Console.ReadLine());

然后背景色变为我写的那种

控制台前景/背景色可以通过属性设置

可用的颜色选项在枚举中定义

我们可以使用从字符串值以编程方式设置这些值

下面是一个快速示例程序,它将根据用户的输入设置
Console.ForgroundColor
Console.BackgroundColor
(如果指定的值不是有效选项,则给出警告)

类程序
{
公共静态无效警告(字符串消息)
{
//获取当前颜色选择
var currentFGColor=Console.ForegroundColor;
var currentBGColor=Console.BackgroundColor;
//设置警告颜色
Console.ForegroundColor=ConsoleColor.Yellow;
Console.BackgroundColor=ConsoleColor.Black;
Console.WriteLine($“{msg}”);
//将颜色设置回当前选择
Console.ForegroundColor=currentFGColor;
Console.BackgroundColor=currentBGColor;
}
静态void Main(字符串[]参数)
{
//获取前台输入
控制台。写入(“前景色:”;
string foregroundColorString=Convert.ToString(Console.ReadLine()).Trim();
//获取背景输入
控制台。写(“背景色:”);
string backgroundColorString=Convert.ToString(Console.ReadLine()).Trim();
if(Enum.TryParse(foregroundColorString,ignoreCase:true,out控制台颜色_foregroundColor))
{
Console.ForegroundColor=\u ForegroundColor;
}
其他的
{
警告(“-无效的ForegroundColor选项:(”);
}
if(Enum.TryParse(backgroundColorString,ignoreCase:true,out ConsoleColor\u backgroundColor))
{
Console.BackgroundColor=\u BackgroundColor;
}
其他的
{
警告(“-无效背景颜色选项:(”);
}
//使用请求的颜色输出到控制台(假设颜色有效)
控制台。WriteLine(“你好,世界!”);
Console.ResetColor();
Console.WriteLine(“\n\n按任意键退出…”);
Console.ReadKey();
}
}