我目前正在想办法处理这种情况,
我想使用某个对象作为字典中的键,因此我需要它
重写 GetHashCode
和 Equals
方法。问题是我的对象的属性之一可为空。
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/