我创建了一个简单的控制台游戏,并很满意它的结果,所以做了一些最后的调整,我想,因为我为背景和文本设置了控制台颜色,我可以让用户选择颜色吗?我知道这可能是一罐蠕虫,但是现在我尝试了一下,但它不会让我设置以下内容,我至少想知道这是否可能。这是我尝试过的。
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
Console.BackgroundColor = ConsoleColor.screen;
Console.ForegroundColor = ConsoleColor.text;
VS给出的错误是ConsoleColor不包含屏幕和文本的定义。
感谢海顿使我走上正轨,提出了以下建议:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
string back = Console.ReadLine();
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), back, true);
正在接收错误的原因是由于ConsoleColor.screen
和ConsoleColor.text
不存在(这是不一样的screen
和text
)。
要获得想要更改控制台颜色的用户,可以尝试以下操作:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
// Attempt to parse the colors that the user entered into their respective enum values.
// The new values of background and foreground will be set to the user input
if(Enum.TryParse(screen, out ConsoleColor background))
{
Console.BackgroundColor = background;
}
if (Enum.TryParse(text, out ConsoleColor foreground))
{
Console.ForegroundColor = foreground;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句