c# - 子类 HashSet 以便它在另一个集合中使用时始终使用某个 IEqualityComparer

标签 c# .net hashset iequalitycomparer

我想继承HashSet<Point>以便它使用 HashSet<Point>.CreateSetComparer()作为IEqualityComparer每当我在另一组中使用它时。

基本上每次我这样做:

var myDict = new Dictionary<MySubclassOfHashSet, Char>();

我希望它自动被视为:

var myDict = new Dictionary<HashSet<Point>, Char>(HashSet<Point>.CreateSetComparer());

根据 this question .

我目前手动完成如下:

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

关于c# - 子类 HashSet 以便它在另一个集合中使用时始终使用某个 IEqualityComparer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14301386/

相关文章:

c# - 如何比较 POCO 之间的字段/属性?

c# - 日历控件 - 以编程方式突出显示日期

c# - 无法使用现有数据库运行 EF5 迁移

Java:基于磁盘的快速哈希集

c# - 使用 XMLTextReader,我如何知道我在哪个元素上?

c# - 如何将静态类中的常量放入 List<SelectListItem>

.net - .net 中的滚动列表

c# - Linux 上的 Mono 和缺少方法异常

java - 从 HashSet 中的 md5 列表中删除文件

node.js - Nodejs Redis HSET & HGET 插入到数据集错误