在开始之前,我想澄清的是,这并不像其他一些“类似”的问题。我试过实现每一种方法,但我在这里遇到的现象确实很奇怪。
我有一个字典,其中ContainsKey总是返回false,即使它们的GetHashCode函数返回相同的输出,即使它们的Equals方法返回true。
这可能意味着什么?我在这里做错什么了?
附加信息
我插入的两个元素都是Owner类型的,没有GetHashCode或Equals方法。这些继承自类型Storable,该类型随后实现接口,并定义了GetHashCode和Equals。
这是我的Storable课。您可能想知道这两个Guid属性是否确实相等--是的,它们是相等的。我仔细检查过了。请参阅后面的示例代码。
public abstract class Storable : IStorable
{
public override int GetHashCode()
{
return Id == default(Guid) ? 0 : Id.GetHashCode();
}
public override bool Equals(object obj)
{
var other = obj as Storable;
return other != null && (other.Id == Id || ReferenceEquals(obj, this));
}
public Guid Id { get; set; }
protected Storable()
{
Id = Guid.NewGuid();
}
}现在,这是我代码的相关部分,字典就是在这里出现的。它接受一个Supporter对象,该对象具有指向Owner的链接。
public class ChatSession : Storable, IChatSession
{
static ChatSession()
{
PendingSupportSessions = new Dictionary<IOwner, LinkedList<IChatSession>>();
}
private static readonly IDictionary<IOwner, LinkedList<IChatSession>> PendingSupportSessions;
public static ChatSession AssignSupporterForNextPendingSession(ISupporter supporter)
{
var owner = supporter.Owner;
if (!PendingSupportSessions.ContainsKey(owner)) //always returns false
{
var hashCode1 = owner.GetHashCode();
var hashCode2 = PendingSupportSessions.First().Key.GetHashCode();
var equals = owner.Equals(PendingSupportSessions.First().Key);
//here, equals is true, and the two hashcodes are identical,
//and there is only one element in the dictionary according to the debugger.
//however, calling two "Add" calls after eachother does indeed crash.
PendingSupportSessions.Add(owner, new LinkedList<IChatSession>());
PendingSupportSessions.Add(owner, new LinkedList<IChatSession>()); //crash
}
...
}
}如果你需要更多的信息,请告诉我。我不知道什么样的信息就足够了,所以我很难包含更多的信息。
发布于 2014-03-20 11:12:31
纪尧姆是对的。在将其中一个键添加到字典后,我似乎正在更改它的值。哈!
发布于 2014-03-20 11:42:12
确保您传递的对象与字典中作为键存储的对象相同。如果您每次都要创建新对象,并且假设对象已经因为类似的值而被存储,那么containsKey将返回false。对象比较与值比较不同。
https://stackoverflow.com/questions/22530582
复制相似问题