我想知道在.NET框架(或其他地方)中是否有任何帮助类将字符转换为ConsoleKey枚举.
e.g 'A' should become ConsoleKey.A
Run Code Online (Sandbox Code Playgroud)
在有人问我为什么要这样做之前.我想写一个带有字符串的帮助器(例如'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());
}
Run Code Online (Sandbox Code Playgroud)
你有没有尝试过:
char a = 'A';
ConsoleKey ck;
Enum.TryParse<ConsoleKey>(a.ToString(), out ck);
Run Code Online (Sandbox Code Playgroud)
所以:
string input = "Hello World";
input.Select(c => (ConsoleKey)Enum.Parse(c.ToString().ToUpper(), typeof(ConsoleKey));
Run Code Online (Sandbox Code Playgroud)
要么
.Select(c =>
{
return Enum.TryParse<ConsoleKey>(a.ToString().ToUpper(), out ck) ?
ck :
(ConsoleKey?)null;
})
.Where(x => x.HasValue) // where parse has worked
.Select(x => x.Value);
Run Code Online (Sandbox Code Playgroud)
还Enum.TryParse()具有一个过载忽略大小写.
| 归档时间: |
|
| 查看次数: |
1824 次 |
| 最近记录: |