首页 > 解决方案 > 无法使用新的 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;
        
    }

}

标签: c#hashcode

解决方案


答案就在问题中,但由于我花了一分钟时间解决问题,所以我会发布一个答案 - 微软的解决方案是正确的,你不能在 .Net Framework 中使用 System.Hashcode。

使用来自nuget的Microsoft.Bcl.HashCode包,它在类中用于较旧的框架 .net 版本。

至于您为什么会遇到这种情况,在不了解您的设置的情况下,您可能有不同的项目具有不同的 .net 版本,或者您可能有一些半编译的 dll。

在 .net 4.8 及之前的版本中,如果 System.Hashcode 存在,它是内部的且不可公开访问,这是您的错误的来源。


推荐阅读