简体   繁体   中英

String (not just letter) to ConsoleKey c#

So i need to convert string to 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)

Please help.

You can convert a string to an enum member using Enum.Parse or Enum.TryParse .

Unfortunately the API is not generic, so you have to specify the type a few times:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM