[英]String (not just letter) to ConsoleKey c#
So i need to convert string to ConsoleKey... 所以我需要将字符串转换为ConsoleKey ...
Yes something like this works: 是的,像这样的作品:
string ch = "a";
ConsoleKey ck = (ConsoleKey)Convert.ToChar(ch);
But what if the string is like "UpArrow" (the string is from ReadKey input and saved to txt file) 但是,如果字符串类似于“ UpArrow”(该字符串来自ReadKey输入并保存到txt文件),该怎么办?
Please help. 请帮忙。
You can convert a string to an enum member using Enum.Parse
or Enum.TryParse
. 您可以使用Enum.Parse
或Enum.TryParse
将字符串转换为枚举成员。
Unfortunately the API is not generic, so you have to specify the type a few times: 不幸的是,API不是通用的,因此您必须多次指定类型:
ConsoleKey key1 = (ConsoleKey)Enum.Parse(typeof(ConsoleKey), "UpArrow");
The above will throw an exception if the string is not a member of the enum. 如果字符串不是枚举的成员,则以上内容将引发异常。 To protect against that you could use: 为了防止这种情况,您可以使用:
if (Enum.TryParse("UpArrow", out ConsoleKey key2))
{
// use 'key2' in here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.