相关疑难解决方法(0)

重写System.Object.GetHashCode的最佳算法是什么?

在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?

.net algorithm hashcode gethashcode

1389
推荐指数
14
解决办法
19万
查看次数

为什么在重写Equals方法时重写GetHashCode很重要?

鉴于以下课程

public class Foo
{
    public int FooId { get; set; }
    public string FooName { get; set; }

    public override bool Equals(object obj)
    {
        Foo fooItem = obj as Foo;

        if (fooItem == null) 
        {
           return false;
        }

        return fooItem.FooId == this.FooId;
    }

    public override int GetHashCode()
    {
        // Which is preferred?

        return base.GetHashCode();

        //return this.FooId.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode

覆盖为什么重要GetHashCode

c# overriding hashcode

1371
推荐指数
13
解决办法
35万
查看次数

在c#中散列数组

简短的问题

如何实现GetHashCode一个Array.

细节

我有一个覆盖的对象Equals,检查:

this.array[n] == otherObject.array[n]
Run Code Online (Sandbox Code Playgroud)

所有narray.

当然,我应该实施补充GetHashCode.我想知道是否有.NET方法可以做到这一点,或者我是否应该实现自己的方式

hash = hash ^ array[n]
Run Code Online (Sandbox Code Playgroud)

澄清

我的对象包含一个数组,我对GetHashCode感兴趣的数组元素.我的数组等价代码仅作为示例 - 就像我的问题所说,但也许我不清楚,我对GetHashCode(不是Equals)感兴趣.我说我自然应该实现补充,GetHashCode因为一旦Equals被覆盖(为了Dictionary正常运行等),实现这一点是.NET的要求.谢谢.

.net c# arrays hash

15
推荐指数
1
解决办法
6344
查看次数

为什么我不能在 IEqualityComparer<Customer> Equals 方法中使用 customer.Name.contains("smith")

我想使用 HashSet.Contains 方法,因为它超级快。

var hashset = new HashSet<Customer>(customers, new CustomerComparer());
var found = hashset.Contains(new Customer{ Id = "1234", Name = "mit" }); // "mit" instead of an equals "smith" in the comparer.
Run Code Online (Sandbox Code Playgroud)

我在客户对象上搜索多个属性。

我必须实现 IEqualityComparer 接口,如:

public class CustomerComparer : IEqualityComparer<Customer>
{
    public bool Equals(Customer x, Customer y)
    {
        return x.Id == y.Id && x.Name.Contains(y.Name);
    }      

    public int GetHashCode(Customer obj)
    {
        return obj.Id.GetHashCode() ^ obj.Name.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我不在 CustomerComparer Equals 方法中使用 Equals 方法(如 .Contains)时,为什么 Equals 方法永远不会命中?

c# iequalitycomparer

1
推荐指数
1
解决办法
69
查看次数