2011-02-03 54 views
0

我嘗試寫的要成功地散列值System.Windows.Input.Key與修改鍵狀態的哈希算法,例如:如何用修飾符鍵狀態成功地散列System.Windows.Input.Key值?

ctrl = false 
shift = true 
alt = false 
capslock = true 
numlock = false 
scroll lock = false 
key: A 

所以像這樣的關鍵值應該從其他不同分開狀態爲ctrl,shift,alt等,但由於這些只是真或假,我不知道如何使它不同的哈希值?

任何想法?它必須足夠獨特,可以處理所有可能的組合鍵。

+1

「不同」和「哈希」是水和火。哈希函數不*保證不同的值。 – 2011-02-03 18:29:15

回答

1

我將建立一個包含能計算出它自己的散列碼,像所有的值類:

class KeyInfo : IEquatable<KeyInfo> 
    { 
     public bool Ctrl { get; private set; } 
     public bool Shift { get; private set; } 
     public bool Alt { get; private set; } 
     public bool CapsLock { get; private set; } 
     public bool NumLock { get; private set; } 
     public bool ScrollLock { get; private set; } 
     public Keys Key { get; private set; } 

     public KeyInfo(bool ctrl, bool shift, bool alt, bool capsLock, bool numLock, bool scrollLock, Keys key) 
     { 
      this.Ctrl = ctrl; 
      this.Shift = shift; 
      this.Alt = alt; 
      this.CapsLock = capsLock; 
      this.NumLock = numLock; 
      this.ScrollLock = scrollLock; 
      this.Key = key; 
     } 

     public override bool Equals(object obj) 
     { 
      return this.Equals(obj as KeyInfo); 
     } 

     public bool Equals(KeyInfo other) 
     { 
      if (other == null) 
       return false; 
      return this.Ctrl == other.Ctrl && this.Shift == other.Shift && 
        this.Alt == other.Alt && this.CapsLock == other.CapsLock && 
        this.NumLock == other.NumLock && this.ScrollLock == other.ScrollLock && 
        this.Key == other.Key; 
     } 

     public override int GetHashCode() 
     { 
      unchecked 
      { 
       int hash = 17; 
       hash = hash * 23 + this.Ctrl.GetHashCode(); 
       hash = hash * 23 + this.Shift.GetHashCode(); 
       hash = hash * 23 + this.Alt.GetHashCode(); 
       hash = hash * 23 + this.CapsLock.GetHashCode(); 
       hash = hash * 23 + this.NumLock.GetHashCode(); 
       hash = hash * 23 + this.ScrollLock.GetHashCode(); 
       hash = hash * 23 + this.Key.GetHashCode(); 
       return hash; 
      } 
     } 
    } 

this Jon Skeet's answerGetHashCode()實施。

N.B.

這個類可以有效地用作Dictionary鍵,分成HashSet或LINQ Distinct()和其他LINQ集的操作。

編輯:

我想執行的事實,你不能使用的哈希碼作爲字典鍵,但使用整個類代替。
您不能依賴散列碼的唯一性,因爲hashing它受到collisions的限制。

+0

感謝digEmAll,看起來像一個堅實的實施。你知道bools本身是否具有特定的GetHashCode實現嗎? – 2011-02-03 18:30:32