【发布时间】:2021-01-28 16:38:09
【问题描述】:
我复制了教授给我的代码,但出现错误“当前上下文中不存在名称 '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;
}
}
【问题讨论】:
-
HashCode是在 .NET Core 2.1 中引入的(请参阅“适用于”in the docs)。您的目标可能是 .NET Framework 或早期版本的 .NET Core。 -
Microsoft 文档说 System.HashCode.Combine() 函数从 .NET 5.0 开始可用。你用的是什么版本?
-
@canton7 .NET Core 不只是 .NET Framework 的一个子集吗?
-
@Josip 是的,您为此使用了什么 .NET?
-
@Quizzarex 不,不是。 .NET Core 是 .NET 的新版本,它取代了 .NET Framework