2012-07-15 88 views
10

我想知道.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()); 
    } 
+2

僅用於字符和數字嗎?你不能有1對1的映射,因爲'ConsoleKey'不區分字符外殼,並且不包含大多數其他的ASCII字符。 – Groo 2012-07-15 20:08:02

+0

是的,這是事實。知道我只有人物和空白。我也會添加句點和逗號。外殼並不重要,因爲這些信息將作爲char直接保存在ConsoleKeyInfo對象中。 – Christoph 2012-07-16 06:13:33

回答

8

你試過:

char a = 'A'; 
ConsoleKey ck; 
Enum.TryParse<ConsoleKey>(a.ToString(), out ck); 

所以:

string input = "Hello World"; 
input.Select(c => (ConsoleKey)Enum.Parse(c.ToString().ToUpper(), typeof(ConsoleKey)); 

.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); 

而且Enum.TryParse()an overload to ignore case

+1

'c.ToString()。ToLower()' - 是不是全部*大寫*? – Ryan 2012-07-15 20:17:22

+0

@minitech:當然,他們只是一個錯字。 – abatishchev 2012-07-15 20:18:32

+0

謝謝,'ToUpper'會更好。在最後一個例子中,'Select'也應該採用兩個通用參數類型,'a'應該改爲'c'。但是我寧願讓一個異常拋出,而不是吞下字符,因爲它可能使它對測試這種方式的恕我直言不那麼有用。 – Groo 2012-07-15 20:21:23

-1

如果是[AZ] & [0-9] OP可以使用它

它可能因爲ConsoleKey是一個enumeration

所以你可以做這樣的事情

char ch = 'A'; 
ConsoleKey ck = (ConsoleKey) ch; 
+5

請解釋爲什麼-1 – HatSoft 2012-07-15 20:02:17

+0

我懷疑它會起作用。例如'(ConsoleKey)「BrowserSearch」'必須拋出異常。 – abatishchev 2012-07-15 20:09:13

+0

@abatishchev請參閱我的更新答案我在完成整個答案之前開始獲得-1。 – HatSoft 2012-07-15 20:10:00

相關問題