加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 告诉HashSet使用IEquatable?

发布时间:2020-12-15 06:31:41 所属栏目:百科 来源:网络整理
导读:我在HashSet上读到的是使用一个类的默认比较器.我希望下面的代码失败,添加第二个Spork到哈希集.我认为我对发生的事情的理解是不完整的.从MSDN的HashSet构造函数: The IEqualityComparer implementation to use when comparing values in the set,or null to
我在HashSet上读到的是使用一个类的默认比较器.我希望下面的代码失败,添加第二个Spork到哈希集.我认为我对发生的事情的理解是不完整的.从MSDN的HashSet构造函数:

The IEqualityComparer implementation to use when comparing values in the set,or null to use the default EqualityComparer implementation for the set type.

那么什么是默认的比较器,我怎么能告诉.Net来使用我自己的比较器?

public class Spork : IEquatable<Spork>
{
    public int Id { get; set; }


    public bool Equals(Spork other)
    {
        return other != null && other.Id == this.Id;
    }

    public override bool Equals(object obj)
    {
        var other = obj as Spork;
        return other != null && other.Id == this.Id;
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

public class Bjork
{
    public static HashSet<Spork> Sporks { get; set; }
    public static void Main()
    {
        Sporks = new HashSet<Spork>();
        Sporks.Add(new Spork() { Id = 0 });
        Sporks.Add(new Spork() { Id = 0 });     // come on,please throw an exception
    }
}

解决方法

它正在使用您的等式方法 – 但是当您尝试添加相等的值时,HashSet<T>.Add不会抛出异常 – 它只返回false.

如果您更改最后两行以打印出Add的返回值,那么您将首次看到它返回True,然后返回False.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读