[英]C# - How to override GetHashCode with Lists in object
我正在尝试创建一个“ KeySet”来修改UIElement行为。 这个想法是创建一个特殊的功能,例如。 用户按住a的同时单击元素。 或Ctrl + a。
到目前为止,我的方法是先为所有可能的修饰符创建一个容器。 如果我只允许一个键,那就没问题了。 我可以用一个简单的字典
Dictionary<Keys, Action> _specialActionList
如果我不贪心,那将是...现在,我当然想要更多。 我想允许多个键或修饰符。 因此,我创建了一个包装器类,其中wich可用作我的字典的键。
使用更复杂的类时存在一个明显的问题。 当前,两个不同的实例将创建两个不同的键,因此他将永远找不到我的函数(请参阅代码以了解,非常明显)
现在,我检查了这篇文章: 包含通用数组的对象的GetHashCode覆盖有所帮助。
但是我的问题是,我的课堂基本设计还可以吗? 我应该使用哈希集来存储修饰符和普通键盘键(而不是列表)。 如果是这样,GetHashCode函数的外观如何?
我知道,要编写很多代码(无聊的哈希函数),一些技巧足以使我入门。 将在这里发布试用版...
到目前为止,代码已经到了,测试显然失败了...
public class KeyModifierSet
{
private readonly List<Key> _keys = new List<Key>();
private readonly List<ModifierKeys> _modifierKeys = new List<ModifierKeys>();
private static readonly Dictionary<KeyModifierSet, Action> _testDict
= new Dictionary<KeyModifierSet, Action>();
public static void Test()
{
_testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing"));
if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)");
}
public KeyModifierSet(IEnumerable<Key> keys, IEnumerable<ModifierKeys> modifierKeys)
{
foreach (var key in keys)
_keys.Add(key);
foreach (var key in modifierKeys)
_modifierKeys.Add(key);
}
public KeyModifierSet(Key key, ModifierKeys modifierKey)
{
_keys.Add(key);
_modifierKeys.Add(modifierKey);
}
public KeyModifierSet(Key key)
{
_keys.Add(key);
}
}
_testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing"));
if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)");
如果我正确理解了您的代码,则希望使用Object.Equals和Object.GetHashCode方法的重写版本测试_testDict字典对象是否相等。 据我所知,您将需要创建自己的自定义集合类型,以覆盖这些方法。
要回答我自己的问题(稍微复杂一点),下面是解决方法:
public class KeyModifierSet
{
internal readonly HashSet<Key> Keys = new HashSet<Key>();
internal readonly HashSet<ModifierKeys> MKeys = new HashSet<ModifierKeys>();
public override int GetHashCode()
{
int hash = Keys.Count + MKeys.Count;
foreach (var t in Keys)
{
hash *= 17;
hash = hash + t.GetHashCode();
}
foreach (var t in MKeys)
{
hash *= 19;
hash = hash + t.GetHashCode();
}
return hash;
}
public override bool Equals(object obj)
{
return Equals(obj as KeyModifierSet);
}
public bool Equals(KeyModifierSet other)
{
// Check for null
if (ReferenceEquals(other, null))
return false;
// Check for same reference
if (ReferenceEquals(this, other))
return true;
// Check for same Id and same Values
return Keys.SetEquals(other.Keys) && MKeys.SetEquals(other.MKeys);
}
public KeyModifierSet(ModifierKeys mKey)
{
MKeys.Add(mKey);
}
public KeyModifierSet(Key key)
{
Keys.Add(key);
}
public KeyModifierSet(Key key, ModifierKeys mKey)
{
Keys.Add(key);
MKeys.Add(mKey);
}
public KeyModifierSet Add(Key key)
{
Keys.Add(key);
return this;
}
public KeyModifierSet Add(ModifierKeys key)
{
MKeys.Add(key);
return this;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.