我想知道.NET框架(或其他地方)中是否有任何帮助类将字符转换为ConsoleKey枚举。是否有一个转换方法需要一个char并产生一个ConsoleKey?
e.g 'A' should become ConsoleKey.A
之前有人问我为什么要这样做。我想编写一个接受字符串的帮助器(例如'Hello World')并将其转换为一系列ConsoleKeyInfo对象。我需要一些疯狂的单元测试,我嘲笑用户输入。
我只是有点厌倦了自己创建胶水代码,所以我想,也许已经有一种方法将char转换为ConsoleKey枚举?
为了完整这里是什么似乎工作的伟大,到目前为止
public static IEnumerable<ConsoleKeyInfo> ToInputSequence(this string text)
{
return text.Select(c =>
{
ConsoleKey consoleKey;
if (Enum.TryParse(c.ToString(CultureInfo.InvariantCulture), true, out consoleKey))
{
return new ConsoleKeyInfo(c, consoleKey, false, false, false);
}
else if (c == ' ')
return new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
return (ConsoleKeyInfo?) null;
})
.Where(info => info.HasValue)
.Select(info => info.GetValueOrDefault());
}
仅用于字符和数字吗?你不能有1对1的映射,因为'ConsoleKey'不区分字符外壳,并且不包含大多数其他的ASCII字符。 – Groo 2012-07-15 20:08:02
是的,这是事实。知道我只有人物和空白。我也会添加句点和逗号。外壳并不重要,因为这些信息将作为char直接保存在ConsoleKeyInfo对象中。 – Christoph 2012-07-16 06:13:33