Subclass HashSet so that it always uses a certain IEqualityComparer when used in another set

孤者浪人 提交于 2019-12-11 02:25:28

问题


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


来源:https://stackoverflow.com/questions/14301386/subclass-hashset-so-that-it-always-uses-a-certain-iequalitycomparer-when-used-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!