Subclass HashSet so that it always uses a certain

2019-07-18 10:55发布

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?

1条回答
狗以群分
2楼-- · 2019-07-18 11:41
    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();
    }
查看更多
登录 后发表回答