gpt4 book ai didi

.net - 使用对象作为字典键

转载 作者:行者123 更新时间:2023-12-01 00:02:47 25 4
gpt4 key购买 nike

我想使用以下对象作为字典键。如果分类 目标 是平等的,关键是平等的。有什么解决办法吗?

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com