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

c# – 使用等于. GetHashCode不是

发布时间:2020-12-15 23:40:23 所属栏目:百科 来源:网络整理
导读:我已经实现了以下课程: public class carComparer : IEqualityComparerCar { public bool Equals(Car car1,Car car2) { if (car1 == null || car2 == null) return false; return (car1.description == car2.description); } public int GetHashCode(Car ca
我已经实现了以下课程:

public class carComparer : IEqualityComparer<Car>
    {
        public bool Equals(Car car1,Car car2)
        {
                if (car1 == null || car2 == null)
                    return false;

                return (car1.description == car2.description);
        }

        public int GetHashCode(Car car)
        {
            unchecked 
            {
                int hash = 17;
                hash = hash * 29 + car.id.GetHashCode();
                hash = hash * 29 + car.description.GetHashCode();
                return hash;
            }
        }

    }

现在看到这个:

Car p1 = new Car() { id = Guid.NewGuid(),description = "Test1" };
        Car p2 = new Car() { id = Guid.NewGuid(),description = "Test1" };
        Car p3 = new Car() { id = Guid.NewGuid(),description = "Test1" };
        Car p4 = new Car() { id = Guid.NewGuid(),description = "Test1" };
        var hash = new HashSet<Car>();
        hash.Add(p1);
        hash.Add(p2);

        var hash2 = new HashSet<Car>();
        hash2.Add(p3);
        hash2.Add(p4);

        var carComparer = new CarComparer();
        Assert.That(hash,Is.EquivalentTo(hash2).Using(carComparer));

我把断点放在.equals和.hashcode中.等于使用;但GetHashCode不是.为什么?

解决方法

您正在使用NUnit Is.EquivalentTo比较两个HashSet.它没有理由调用GetHashCode – 它基本上比较了两个集合的成员是否相等.这就是为什么从不调用GetHashCode并调用Equals来比较来自不同HashSets的两个项目的相等性.您的哈希集也可以是列表或任何其他可枚举的 – 在比较两个集合时不会改变任何内容.

您可能希望在向HashSet添加项目时调用GetHashCode – 但事实并非如此,因为此时您的carComparer尚未知晓 – 您不会将其传递给HashSet构造函数.如果你这样做:

var hash = new HashSet<Car>(new carComparer());

然后在将新项添加到相应的HashSet时将调用GetHashCode.

(编辑:李大同)

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

    推荐文章
      热点阅读