如何使用修饰键状态成功散列System.Windows.Input.Key值?

时间:2011-02-03 18:08:37

标签: c# .net hash gethashcode

我正在尝试编写一个散列算法,该算法将使用修饰键状态成功散列System.Windows.Input.Key值,例如:

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

所以像这样的键值应该与ctrl,shift,alt等不同状态的其他值分开。但是由于这些只是真或假,我不知道如何使它与哈希值区别开来? / p>

有什么想法吗?它必须足够独特,以处理所有可能的键组合。

1 个答案:

答案 0 :(得分: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;
            }
        }
    }

GetHashCode()实施的this Jon Skeet's answer致谢。

N.B。

此类可以有效地用作Dictionary密钥,HashSet或LINQ Distinct()以及其他LINQ集'操作。

修改

我想强制执行以下事实:您不能将哈希码用作字典键,而是使用整个类。
您不能依赖哈希码的唯一性,因为hashing它受collisions的约束。