Subclass HashSet so that it always uses a certain

2019-07-18 11:18发布

问题:

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:

    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();
    }