c# - 无法使用新的 HashCode 覆盖类中的 GetHashCode
问题描述
我复制了教授给我的代码,但出现错误“当前上下文中不存在名称 'HashCode”。我读到了一些东西,我认为它应该可以工作。我正在使用 VisualStudio 2019。该行在下面标记。
Visual 给我的潜在修复之一是安装包 Microsoft.Bcl.HashCode,但正如 Microsoft 文档所说,它应该已经在 System 中。
自从最近添加以来,没有发现任何关于此的内容。有一些用途(和我的一样),但不知道为什么我的不起作用。
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;
}
}
解决方案
答案就在问题中,但由于我花了一分钟时间解决问题,所以我会发布一个答案 - 微软的解决方案是正确的,你不能在 .Net Framework 中使用 System.Hashcode。
使用来自nuget的Microsoft.Bcl.HashCode包,它在类中用于较旧的框架 .net 版本。
至于您为什么会遇到这种情况,在不了解您的设置的情况下,您可能有不同的项目具有不同的 .net 版本,或者您可能有一些半编译的 dll。
在 .net 4.8 及之前的版本中,如果 System.Hashcode 存在,它是内部的且不可公开访问,这是您的错误的来源。
推荐阅读
- javascript - 使用正则表达式值验证密码时出错?
- javascript - 单击时触发工具提示
- google-bigquery - BigQuery 在位置找不到现有表
- jenkins - 创建空文件时未将 Ebextensions 部署到 AWS Beanstalk
- c++ - 对 C++ 中的复制构造函数和对象感到困惑
- javascript - 在浏览器上,无法在最新的三星 s10 和 s20 手机中使用 navigator.getusermedia js 访问后置摄像头(注:最新手机中的 3 个后置摄像头)
- c - 为什么将 SIGTTOU 信号传递给进程?
- java - ES错误:请求处理失败;[172.17.1.128:9300][索引:数据/读取/搜索[相位/dfs]]];
- java - 我的通知频道未创建
- postal-code - 操作系统数据中心 - 网格参考中的邮政编码