gpt4 book ai didi

c# - GetHashCode 覆盖包含通用数组的对象

转载 作者:IT王子 更新时间:2023-10-29 03:47:46 34 4
gpt4 key购买 nike

我有一个包含以下两个属性的类:

public int Id      { get; private set; }
public T[] Values { get; private set; }

我做到了IEquatable<T>并覆盖 object.Equals像这样:

public override bool Equals(object obj)
{
return Equals(obj as SimpleTableRow<T>);
}

public bool Equals(SimpleTableRow<T> other)
{
// Check for null
if(ReferenceEquals(other, null))
return false;

// Check for same reference
if(ReferenceEquals(this, other))
return true;

// Check for same Id and same Values
return Id == other.Id && Values.SequenceEqual(other.Values);
}

当覆盖 object.Equals 时我还必须覆盖 GetHashCode当然。但是我应该实现什么代码呢?如何从通用数组创建哈希码?我如何将它与 Id 结合起来?整数?

public override int GetHashCode()
{
return // What?
}

最佳答案

由于此线程中出现的问题,我发布了另一个回复,展示了如果你弄错了会发生什么......主要是,你不能使用数组的 GetHashCode();正确的行为是运行它时不会打印任何警告...切换注释以修复它:

using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static void Main()
{
// first and second are logically equivalent
SimpleTableRow<int> first = new SimpleTableRow<int>(1, 2, 3, 4, 5, 6),
second = new SimpleTableRow<int>(1, 2, 3, 4, 5, 6);

if (first.Equals(second) && first.GetHashCode() != second.GetHashCode())
{ // proven Equals, but GetHashCode() disagrees
Console.WriteLine("We have a problem");
}
HashSet<SimpleTableRow<int>> set = new HashSet<SimpleTableRow<int>>();
set.Add(first);
set.Add(second);
// which confuses anything that uses hash algorithms
if (set.Count != 1) Console.WriteLine("Yup, very bad indeed");
}
}
class SimpleTableRow<T> : IEquatable<SimpleTableRow<T>>
{

public SimpleTableRow(int id, params T[] values) {
this.Id = id;
this.Values = values;
}
public int Id { get; private set; }
public T[] Values { get; private set; }

public override int GetHashCode() // wrong
{
return Id.GetHashCode() ^ Values.GetHashCode();
}
/*
public override int GetHashCode() // right
{
int hash = Id;
if (Values != null)
{
hash = (hash * 17) + Values.Length;
foreach (T t in Values)
{
hash *= 17;
if (t != null) hash = hash + t.GetHashCode();
}
}
return hash;
}
*/
public override bool Equals(object obj)
{
return Equals(obj as SimpleTableRow<T>);
}
public bool Equals(SimpleTableRow<T> other)
{
// Check for null
if (ReferenceEquals(other, null))
return false;

// Check for same reference
if (ReferenceEquals(this, other))
return true;

// Check for same Id and same Values
return Id == other.Id && Values.SequenceEqual(other.Values);
}
}

关于c# - GetHashCode 覆盖包含通用数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/638761/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com