如何解决不能使用新的 HashCode 覆盖类中的 GetHashCode
我已经复制了教授给我的代码,但出现错误“名称'HashCode 在当前上下文中不存在”。我读了一些关于它的东西,我认为它应该有效。我使用的是 VisualStudio 2019。该行在下方标记。
Visual 给我的潜在修复之一是安装包 Microsoft.Bcl.HashCode,但正如 Microsoft 文档所说,它应该已经在系统中。
没有发现任何关于此的信息,因为它是最近添加的。有一些用途(和我的一样),但不知道为什么我的不起作用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LV6.Zad3 {
public class Car : IEquatable<Car>
{
public string Make { get; private set; }
public string Model { get; private set; }
public int Km { get; private set; }
public int Year { get; private set; }
public Car(string brand,string type,int km,int year)
{
Make = brand;
Model = type;
Km = km;
Year = year;
}
public override string ToString() => $"{Make} - {Model} - {Km} - {Year}";
public override int GetHashCode() => HashCode.Combine(Make,Model,Km,Year); // I this line <--
public override bool Equals(object obj){
if (obj is Car == false) return false;
return this.Equals((Car) obj);
}
public bool Equals(Car other) => this.Make == other.Make &&
this.Model == other.Model &&
this.Year == other.Year &&
this.Km == other.Km;
}
}
解决方法
如果 HashCode
不可用,因为这不是 .NET Core
应用,那么您可以使用自定义实现。下面的示例基于 on this accepted answer。
public class Car : IEquatable<Car>
{
public string Make { get; private set; }
public string Model { get; private set; }
public int Km { get; private set; }
public int Year { get; private set; }
public Car(string brand,string type,int km,int year)
{
Make = brand;
Model = type;
Km = km;
Year = year;
}
public override string ToString() => $"{Make} - {Model} - {Km} - {Year}";
#region IEquatable Members
/// <summary>
/// Equality overrides from <see cref="System.Object"/>
/// </summary>
/// <param name="obj">The object to compare this with</param>
/// <returns>False if object is a different type,otherwise it calls <code>Equals(Car)</code></returns>
public override bool Equals(object obj)
{
if (obj is Car other)
{
return Equals(other);
}
return false;
}
/// <summary>
/// Checks for equality among <see cref="Car"/> classes
/// </summary>
/// <param name="other">The other <see cref="Car"/> to compare it to</param>
/// <returns>True if equal</returns>
public virtual bool Equals(Car other)
=> this.Make == other.Make &&
this.Model == other.Model &&
this.Year == other.Year &&
this.Km == other.Km;
/// <summary>
/// Calculates the hash code for the <see cref="Car"/>
/// </summary>
/// <returns>The int hash value</returns>
public override int GetHashCode()
{
unchecked
{
int hc = -1817952719;
hc = (-1521134295)*hc + Make.GetHashCode();
hc = (-1521134295)*hc + Model.GetHashCode();
hc = (-1521134295)*hc + Year.GetHashCode();
hc = (-1521134295)*hc + Km.GetHashCode();
return hc;
}
}
#endregion
}
或者使用Tuple<>
使用的哈希码组合
// System.Tuple
internal static int CombineHashCodes(int h1,int h2)
{
return ((h1 << 5) + h1) ^ h2;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。