我想继承HashSet<Point>
以便它使用 HashSet<Point>.CreateSetComparer()
作为IEqualityComparer
每当我在另一组中使用它时。
基本上每次我这样做:
var myDict = new Dictionary<MySubclassOfHashSet, Char>();
我希望它自动被视为:
var myDict = new Dictionary<HashSet<Point>, Char>(HashSet<Point>.CreateSetComparer());
根据 this question .
我目前手动完成如下:
class MySubclassOfHashSet: HashSet<Point> {
public override bool Equals(object obj) {
//...
}
public override int GetHashCode() {
//...
}
}
但是有点丑。有没有我想念的更简单的方法?
最佳答案
var myDict = new Dictionary<MySubclassOfHashSet<Point>, Char>();
public sealed class MySubclassOfHashSet<T> : HashSet<T>, IEquatable<MySubclassOfHashSet<T>>
{
public override int GetHashCode()
{
return Unique.GetHashCode(this);
}
public bool Equals(MySubclassOfHashSet<T> other)
{
return Unique.Equals(this, other);
}
private static readonly IEqualityComparer<HashSet<T>> Unique = HashSet<T>.CreateSetComparer();
}
关于c# - 子类 HashSet 以便它在另一个集合中使用时始终使用某个 IEqualityComparer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14301386/