【发布时间】:2011-12-29 20:32:20
【问题描述】:
我有一个这样的实体类(缺少很多东西):
class Parent
{
private readonly Iesi.Collections.Generic.ISet<Child> children =
new Iesi.Collections.Generic.HashedSet<Child>();
public virtual void AddChild(Child child)
{
if (!this.children.Contains(child))
{
this.children.Add(child);
child.Parent = this;
}
}
public virtual void RemoveChild(Child child)
{
if (this.children.Contains(child))
{
child.Parent = null;
this.children.Remove(child);
}
}
}
但是,当我尝试删除一个孩子时,if 语句的计算结果为 false。所以,我在if 语句上放了一个断点,并评估了某些表达式:
this.children.Contains(child) => false
this.children.ToList()[0].Equals(child) => true
this.children.ToList()[0].GetHashCode() => 1095838920
child.GetHashCode() => 1095838920
我的理解是,如果GetHashCode 返回相同的值,它会检查Equals。为什么Contains返回false?
我的Parent 和Child 实体都继承自一个通用的Entity 基类,它是NHibernate 3.0 Cookbook 第25 页中通用实体基类的非通用版本。这是我的基类:
public class Entity : IEntity
{
public virtual Guid Id { get; private set; }
public override bool Equals(object obj)
{
return Equals(obj as Entity);
}
private static bool isTransient(Entity obj)
{
return obj != null &&
Equals(obj.Id, Guid.Empty);
}
private Type getUnproxiedType()
{
return GetType();
}
public virtual bool Equals(Entity other)
{
if (other == null)
return false;
if (ReferenceEquals(this, other))
return true;
if (!isTransient(this) &&
!isTransient(other) &&
Equals(Id, other.Id))
{
var otherType = other.getUnproxiedType();
var thisType = getUnproxiedType();
return thisType.IsAssignableFrom(otherType) ||
otherType.IsAssignableFrom(thisType);
}
return false;
}
public override int GetHashCode()
{
if (Equals(Id, Guid.Empty))
return base.GetHashCode();
return Id.GetHashCode();
}
}
经过进一步调查,我觉得发生了这样的事情:
- 致电
parent.AddChild(child) - 保存到数据库,导致生成
child.Id - 致电
parent.RemoveChild(child)
...如下所述,这正在改变GetHashCode()。
这是我的程序中的一个错误的结果 - 我应该在第 2 步和第 3 步之间重新加载 parent。
不过,我认为还有更根本的错误。
【问题讨论】:
-
出于好奇,你能用
private Iesi.Collections.Generic.HashedSet<Child> children = new Iesi.Collections.Generic.HashedSet<Child>();测试一下吗
标签: c# nhibernate equals contains gethashcode