我正在尝试为我的班级创建一个自定义比较器:
using System.Collections.Generic;
namespace i.changed.namespaces.DataStructures
{
public class Edge
{
public Cords startPoint, endPont;
public double length;
//more code here that doesnt matter
}
public class EdgeComparer : IEqualityComparer<Edge>
{
public bool Equals(Edge x, Edge y)
{
//Check whether the objects are the same object.
if (x.Equals(y)) return true;
return x.startPoint.Equals(y.startPoint) && x.endPont.Equals(y.endPont) && (x.length - y.length < 0.0001);
}
public int GetHashCode(Edge obj)
{
int hash = 17;
hash = hash * 23 + obj.length.GetHashCode();
hash = hash * 23 + obj.startPoint.GetHashCode();
hash = hash *23 + obj.endPont.GetHashCode();
return hash;
}
}
Run Code Online (Sandbox Code Playgroud)
}
我在另一个对象中使用此类:
using i.changed.namespaces.DataStructures;
namespace i.changed.namespaces
public class MyClass
{
HashSet<Edge> Edges, NewEdges;
public MyClass()
{
NewEdges = new HashSet<Edge>();
Edges = new HashSet<Edge>();
}
Run Code Online (Sandbox Code Playgroud)
在某些时候我想得到这个哈希集的并集:
newEdges.UnionWith(Edges);
Run Code Online (Sandbox Code Playgroud)
但看起来它从来没有以这种方式使用我的 EdgeComparer 。我究竟做错了什么?
HashSet<T>提供构造函数,您可以在其中传递IEqualityComparer<T>. 如果你传递它,那么它将被使用,否则HashSet<T>将使用 default 构造IEqualityComparer<T>。
问题的解决方案是稍微修改您的代码并将其传递EdgeComparer到HasSet<Edge>构造函数中
public MyClass()
{
NewEdges = new HashSet<Edge>(new EdgeComparer());
Edges = new HashSet<Edge>(new EdgeComparer());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3103 次 |
| 最近记录: |