2011-09-17 57 views
1

我需要在控制檯應用程序中處理來自用戶的輸入,並且我需要僅允許Z字段編號(...,-1,0,1,...)。
我已經建立了這個過程從用戶字符char,通過保持最後的字符我可以驗證順序是正確的。最終用戶必須輸入一組Z值,例如
-3 6 7 101 -500
我的問題是與LastInput作爲enum比較,這意味着我想檢查是否最後輸入是Numeric | Space | ...請看看代碼。在枚舉中使用按位或運算

public void Foo() 
{ 
    ConsoleKeyInfo key; 
    var chars = new List<char>(); 
    NextChar last = NextChar.Space; 
    var list = new List<NextChar> {last}; 

    do 
    { 
     key = Console.ReadKey(true); 
     NextChar next = ProcessCharInput(key.KeyChar); 
     switch (next) 
     { 
      case NextChar.None: 
      if(key.Key != ConsoleKey.Enter) 
      { 
       return; 
      } 
      continue; 

      case NextChar.Space: 
      if (last == (NextChar.Numeric)) 
      { 
       Console.Write(key.KeyChar); 
       last = next; 
       chars.Add(key.KeyChar); 
      } 

      break; 
      case NextChar.Minus: 
      if (last == (NextChar.Space)) 
      { 
       Console.Write(key.KeyChar); 
       last = next; 
       chars.Add(key.KeyChar); 
      } 
      break; 
      case NextChar.Numeric: 
      if (last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)) 
      { 
       Console.Write(key.KeyChar); 
       last = next; 
       chars.Add(key.KeyChar); 
      } 
      break; 
      default: 
      throw new ArgumentOutOfRangeException(); 
     } 
    } 
    while (true); 
} 

[Flags] 
private enum NextChar 
{ 
    None = 0x0, 
    Space = 0x1, 
    Minus = 0x2, 
    Numeric = 0x4 
} 

我猜測,我做錯了什麼用枚舉,因爲Numeric和輸入最後是Space我不能讓last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)是真實的。

回答

3

你確定你試圖做一個按位或?

0100 OR 0010 OR 0001 = 0111 

這似乎沒有幫助。看起來你很可能在這裏嘗試布爾邏輯。在這種情況下,你會想改變

last == (NextChar.Numeric | NextChar.Minus | NextChar.Space)

last == NextChar.Numeric || last == NextChar.Minus || last == NextChar.Space 

...當然,說實話,如果你限制爲一組4個值的和你試圖以確保你做的東西對他們的3,你可能更加清晰,表現力與

if(last != NextChar.None) 
+0

謝謝,它現在很明顯。我不知道我是如何錯過它的。計算機科學的第一天 – guyl

2

下面的幾行說明了這將如何解釋:

last == (NextChar.Numeric | NextChar.Minus | NextChar.Space) 
last == (4 | 2 | 1) // Same meaning with the constants in place. 
last == 7 // Same meaning, with the or calculated. 

你想要什麼大概是這樣的:

last == NextChar.Numeric || last == NextChar.Minus || last == NextChar.Space 

或按位邏輯:

last & (NextChar.Numeric | NextChar.Minus | NextChar.Space) != 0 
2

要使用的位標誌的一般模式是<comparison value> <operation> (value & mask))。具體爲您的情況:

if(NextChar.None != (last & (NextChar.Numeric | NextChar.Minus | NextChar.Space))) { ... }