子类HashSet,以便在另一个集合中使用时始终使用某个IEqualityComparer [英] Subclass HashSet so that it always uses a certain IEqualityComparer when used in another set
本文介绍了子类HashSet,以便在另一个集合中使用时始终使用某个IEqualityComparer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对HashSet<Point>
进行子类化,以便每当在另一个集合中使用它时,都将HashSet<Point>.CreateSetComparer()
用作IEqualityComparer
.
基本上每次我这样做:
var myDict = new Dictionary<MySubclassOfHashSet, Char>();
我希望它被自动视为:
var myDict = new Dictionary<HashSet<Point>, Char>(HashSet<Point>.CreateSetComparer());
根据此问题.>
我目前手动执行以下操作:
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();
}
I want to subclass HashSet<Point>
so that it uses HashSet<Point>.CreateSetComparer()
as an IEqualityComparer
whenever I use it inside another set.
Basically every time I do this:
var myDict = new Dictionary<MySubclassOfHashSet, Char>();
I want it automatically treated as :
var myDict = new Dictionary<HashSet<Point>, Char>(HashSet<Point>.CreateSetComparer());
As per this question.
I have currently done this manually as follows:
class MySubclassOfHashSet: HashSet<Point> {
public override bool Equals(object obj) {
//...
}
public override int GetHashCode() {
//...
}
}
But it's kind of ugly. Is there an easier way that I'm missing?
解决方案
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();
}
这篇关于子类HashSet,以便在另一个集合中使用时始终使用某个IEqualityComparer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文