2

我想子类化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() {
      //...
    }
}

但这有点丑。有没有我想念的更简单的方法?

4

1 回答 1

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();
    }
于 2013-12-24T04:02:53.197 回答