当前位置: 首页 > 编程语言 > C#

使用对象的HashSet检查相等性

时间:2023-04-11 02:34:19 C#

使用对象的HashSet检查相等性我正在尝试比较两个定义类型为EqualityComparer.Default.Equals(value,oldValue)的HashSet。定义定义如下publicclassDefinition{publicstringVariable{get;放;}publicHashSetLocationList{get;放;}publicoverrideboolEquals(objectobj){Definitionother=objasDefinition;返回other.Variable.Equals(this.Variable)&&other.LocationList!=null&&this.LocationList!=null&&other.LocationList.Count==this.LocationList.Count&&other.LocationList==this.LocationList;}publicoverrideintGetHashCode(){returnthis.Variable.GetHashCode()^this.LocationList.Count.GetHashCode();//^this.LocationList.GetHashCode();}}publicclassLocation{publicintLine{get;放;}publicintColumn{得到;放;}publicintPosition{得到;放;}publicstringCodeTab{得到;放;}publicLocation(intline,intcol,intpos,stringtab){Line=line;列=列;位置=位置;CodeTab=制表符;}publicoverrideboolEquals(objectobj){Locationother=objasLocation;返回这个.CodeTab==other.CodeTab&&this.Position==other.Position&&this.Column==other.Column&&this.Line==other.Line;}publicoverrideintGetHashCode(){returnthis.CodeTab.GetHashCode()^this.Position.GetHashCode()^this.Column.GetHashCode()^this.Line.GetHashCode();不知何故,对于类似的集合,结果返回为false,尽管所有信息都保持不变唯一的区别是,某些元素的位置被交换了,但我知道HashSet在比较时不保留或检查顺序。谁能告诉我这里出了什么问题?PS:我尝试取消注释this.LocationList.GetHashCode(),但没有用。您需要为集合创建一个比较器:varsetComparer=HashSet.CreateSetComparer();返回other.Variable.Equals(this.Variable)&&setComparer.Equals(this.LocationList,other.LocationList);EqualityComparer.Default将寻找一个实现IEquatable对象的对象。否则,它遵从检查引用相等性的ObjectEqualityComparer。这就是您在比较参考时看到错误的原因。您真正想要做的是显式实现IEquatable。请注意,您应该使您的属性不可改变,以使其正常工作:publicclassLocation:IEquatable{publicLocation(intline,intcol,intpos,stringtab){Line=line;列=列;位置=位置;CodeTab=制表符;}publicintLine{得到;私有集;}publicintColumn{得到;私有集;}publicintPosition{得到;私有集;}publicstringCodeTab{得到;私有集;}publicboolEquals(Locationother){if(ReferenceEquals(null,other))returnfalse;如果(ReferenceEquals(this,other))返回true;returnstring.Equals(CodeTab,other.CodeTab)&&Column==other.Column&&Line==other.Line&&Position==other.Position;}publicoverrideboolEquals(objectobj){if(ReferenceEquals(null,obj))returnfalse;如果(ReferenceEquals(this,obj))返回真;如果(obj.GetType()!=this.GetType())返回false;返回等于((位置)对象);}publicstaticbooloperator==(Locationleft,Locationright){returnEquals(left,right);}公共静态布尔运算符!=(左位置,右位置){return!Equals(left,right);}publicoverrideintGetHashCode(){unchecked{varhashCode=(CodeTab!=null?CodeTab.GetHashCode():0);hashCode=(hashCode*397)^Column;hashCode=(hashCode*397)^行;hashCode=(hashCode*397)^位置;返回哈希码;现在如果你查看Default创建的EqualityComparer的类型,你会看到GenericEqualityComparer:以上是C#学习教程:检查对象的HashSet是否相等,分享所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注—Console.WriteLine(EqualityComparer.Default.GetType())位置。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: