c# - 当属性之一可以为 null 时 GetHashCode

标签 c# .net hashcode .net-4.8 gethashcode

我目前正在想办法处理这种情况, 我想使用某个对象作为字典中的键,因此我需要它 重写 GetHashCodeEquals 方法。问题是我的对象的属性之一可为空。

public class Car
{
   public int Id { get; set; }
   public CarBodyType Type { get; set; }

   public int? LifeSpanInYears { get; set; }


   public override bool Equals(object o)
   {
      // ...
   }

   public override int GetHashCode()
   {
      var result = base.GetHashCode();
      result = (result * 397) ^ this.Id.GetHashCode();
      result = (result * 397) ^ this.Type.GetHashCode();

      // Here ... What is the best approach? Currently, result will be 1 if LifeSpanInYears is null.
      result = (result * 397) ^ (this.LifeSpanInYears?.GetHashCode() ?? 0);

      return result;
   }
}

处理某个属性可能为空值时的最佳方法是什么? 我认为这将是最好的方法。

if (this.LifeSpanInYears.HasValue)
{
   result = (result * 397) ^ this.LifeSpanInYears.GetHashCode();
}

至少我会解决这个问题,每次任何可为 null 的属性为 null 时,GetHashCode 的结果都是 1。

您对此有何看法?

非常感谢您的回复。

最佳答案

您可以考虑使用内置的 HashCode结构:

public override int GetHashCode()
{
    HashCode hashCode = new();
    hashCode.Add(this.Id);
    hashCode.Add(this.Type);
    hashCode.Add(this.LifeSpanInYears);
    return hashCode.ToHashCode();
}

...或:

public override int GetHashCode()
{
    return HashCode.Combine(this.Id, this.Type, this.LifeSpanInYears);
}

它负责处理可为空的值。您不必为他们做任何特别的事情。

我预计它会比您的乘法+异或方法慢,但它应该会产生质量更好的哈希码。 HashCode 结构体的源代码为 here .

注意:HashCode 类型在 .NET Core 2.1 及更高版本中可用。

关于c# - 当属性之一可以为 null 时 GetHashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73925136/

相关文章:

c# - 另一个“为此有设计模式吗?”

java - 证明 : why does java. lang.String.hashCode() 的实现与其文档相匹配?

c# - 简单的 LinQ 问题 : convert [][] to []

c# - 获取泛型类的子类型列表

.net - WinDbg SOS异常堆栈中函数地址旁边的+0x10是什么意思?

c# - 如何在传递接口(interface)时访问不同具体类的属性

c# - php 和 c# 中的 hmac_sha256 不同

java - 可靠且快速的文件重复识别方法

c# - 如何合并文件夹中所有 Excel 文件的已用范围?

.net - .NET Framework 4.5 是否适用于 Windows Server 2003?