【发布时间】:2016-07-11 21:23:51
【问题描述】:
我有一个对象 List<IReportRelationMapping> 的列表,我需要检查该列表是否不包含特定的 ReportRelationMapping 对象
这是我的ReportRelationMapping 的样子
public class ReportRelationMapping : IReportRelationMapping
{
public string Name { get; set; }
public IReportRelation LocalRelation { get; set; }
public IReportRelation ForeignRelation { get; set; }
public IReportRelationMapping RelatedThrough { get; set; }
}
列表包含一个对象 if this.LocalRelation == passed.LocalRelation && this.ForeignRelation == passed.ForeignRelation 或 this.LocalRelation == passed.ForeignRelation && this.ForeignRelation == passed.LocalRelation
这是我为覆盖列表的Contains 属性所做的操作
public class ReportRelationMapping : IReportRelationMapping
{
public string Name { get; set; }
public IReportRelation LocalRelation { get; set; }
public IReportRelation ForeignRelation { get; set; }
public IReportRelationMapping RelatedThrough { get; set; }
public bool Equals(ReportRelationMapping other)
{
if (other == null)
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
return (this.LocalRelation == other.LocalRelation && this.ForeignRelation == other.ForeignRelation)
|| (this.LocalRelation == other.ForeignRelation && this.ForeignRelation == other.LocalRelation);
}
public override bool Equals(object other)
{
if (other == null)
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
if (this.GetType() != other.GetType())
{
return false;
}
return this.Equals(other as ReportRelationMapping);
}
public override int GetHashCode()
{
int hash = 14;
hash = (hash * 7) + this.ForeignRelation.GetHashCode();
return (hash * 7) + this.LocalRelation.GetHashCode();
}
public static bool operator ==(ReportRelationMapping lhs, ReportRelationMapping rhs)
{
// Check for null on left side.
if (Object.ReferenceEquals(lhs, null))
{
if (Object.ReferenceEquals(rhs, null))
{
// null == null = true.
return true;
}
// Only the left side is null.
return false;
}
// Equals handles case of null on right side.
return lhs.Equals(rhs);
}
public static bool operator !=(ReportRelationMapping lhs, ReportRelationMapping rhs)
{
return !(lhs == rhs);
}
}
但由于某种原因,即使列表包含给定对象,我也会得到false 或“不包含该对象”。当我调试我的代码时,我可以看到调试器到达Equal 方法,所以它通过我的代码,但它永远不会到达GetHashCode 方法。我不确定我是否在这里错误地实现了我的GetHashCode 方法。
我在这里错过了什么?在我的情况下,为什么包含总是返回“不包含”?
如何正确覆盖列表的 Contains 方法?
【问题讨论】:
-
好吧,您的哈希码与 Equals 不匹配,因为它应该为两个相等的对象返回相同的东西。哈希应该更像
return this.ForeignRelation.GetHashCode() + this.LocalRelation.GetHashCode();
标签: c# list overriding contains gethashcode