我想使用以下对象作为字典键。如果分类 和 目标 是平等的,关键是平等的。有什么解决办法吗?
public class TargetKey
{
public TargetKey(Categories category_arg, String target_arg)
{
catetory = category_arg;
target = target_arg;
}
private Categories catetory;
public Categories Catetory
{
get { return catetory; }
//set { catetory = value; }
}
private String target;
public String Target
{
get { return target; }
//set { target = value; }
}
}
糟糕的解决方案
好像
GetHashCode()
首先调用,如果哈希等于,则 Equals()
叫做。所以我添加了以下两种方法:
public override bool Equals(object obj)
{
TargetKey other = obj as TargetKey;
return other.Catetory == this.Catetory && other.Target == this.Target;
}
public override int GetHashCode()
{
return 0; //this will leads to ONLY 1 bucket, which defeat the idea of Dictionary.
}
精制方案
public override bool Equals(object obj)
{
TargetKey other = obj as TargetKey;
return other.Catetory == this.Catetory && other.Target == this.Target;
}
public override int GetHashCode()
{
Int32 hash = this.Target.GetHashCode() + this.Catetory.GetHashCode();
// This will introduce some more buckets. Though may not be as many as possible.
return hash;
}
最佳答案
覆盖和实现 Equals()
和 GetHashCode()
基于您的类别和目标,这将允许它们作为字典的键用于比较。
这是一个建议的实现,但究竟需要做什么取决于它们是否可以为空。我假设它们可以在下面的实现中,因为构造函数中没有空检查:
public class TargetKey
{
public TargetKey(Categories category_arg, String target_arg)
{
Catetory = category_arg;
Target = target_arg;
}
private Categories catetory;
public Categories Catetory
{
get { return catetory; }
}
private String target;
public String Target
{
get { return target; }
}
public bool Equals (TargetKey other)
{
if (ReferenceEquals (null, other))
{
return false;
}
if (ReferenceEquals (this, other))
{
return true;
}
return Equals (other.catetory, catetory) && Equals (other.target, target);
}
public override bool Equals (object obj)
{
if (ReferenceEquals (null, obj))
{
return false;
}
if (ReferenceEquals (this, obj))
{
return true;
}
if (obj.GetType () != typeof (TargetKey))
{
return false;
}
return Equals ((TargetKey) obj);
}
public override int GetHashCode ()
{
unchecked
{
return ((catetory != null ? catetory.GetHashCode () : 0)*397) ^ (target != null ? target.GetHashCode () : 0);
}
}
}
关于.net - 使用对象作为字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430888/