将String转换为System.ConsoleColor [英] Convert String to System.ConsoleColor

查看:101
本文介绍了将String转换为System.ConsoleColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我已经在COnsole应用程序中编写了一个代码,用户必须在其中输入颜色名称,当按下输入并写入一些forground颜色时,用户将输入颜色。



Hey i have Writen a Code in COnsole Application in which user have to Enter a Color name and when it press enter and write something forground color will be the enter color by user.

Console.WriteLine("Enter the Name of Color in Which do You Want to Print");
                  string str = Console.ReadLine();

                  Console.ForegroundColor = (ConsoleColor) str;





但它给出错误错误: - 无法转换类型'string'到'System.ConsoleColor'

任何想法如何将字符串转换为System.ConsoleColor



but it gives error Error:- Cannot convert type 'string' to 'System.ConsoleColor'
any idea how can i convert string to System.ConsoleColor

推荐答案

ShilpaKumario写道:
ShilpaKumario wrote:

Console.ForegroundColor =(ConsoleColor)str;

Console.ForegroundColor = (ConsoleColor) str;



你可能很容易发现自己在阅读文档 [ ^ ],你应该使用:




As you may easily find yourself reading the documentation[^], you should use:

(ConsoleColor) Enum.Parse(typeof(ConsoleColor), str);



:)


:)


虽然有几个人(到目前为止4)已经回答了你的问题,你最好不要这样做。当您要求用户输入颜色名称时,可能会出现拼写错误。一个更好的选择是给他们一个颜色列表,并要求他们从该列表中选择。我假设您展示的代码片段用于测试目的,并且您的实际代码具有某种适当的UI。
While several people (4 so far) have answered your question, you'd be better off not doing it this way. There may be typos when you ask users to type in the name of color. A better option would be to give them a list of colors and ask them to choose from that list. I assume the code snippet you showed was for test purposes and that your actual code has some kind of proper UI.


Console.WriteLine("Enter the Name of Color in Which do You Want to Print");
           string str = Console.ReadLine();
           Console.ForegroundColor =(ConsoleColor) Enum.Parse(typeof(ConsoleColor), str,true);
           Console.Read()


这篇关于将String转换为System.ConsoleColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆