在C#中从排序的字典中获取数据时出错
作者:互联网
我有一个SortedDictionary< Package,List< string>>.以下是Package类:
using System;
namespace GetPackageInfo
{
public class Package : IComparable, IEquatable<Package>
{
public string PackageName;
public string Version;
public Package()
{
}
public Package(string packageName)
{
this.PackageName = packageName;
}
public override int GetHashCode()
{
unchecked
{
int result = 17;
result = result * 23 + ((PackageName != null) ? this.PackageName.GetHashCode() : 0);
result = result * 23 + ((Version != null) ? this.Version.GetHashCode() : 0);
return result;
}
}
public bool Equals(Package other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(this.PackageName, other.PackageName) &&
Equals(this.Version, other.Version);
}
public override bool Equals(object obj)
{
Package temp = obj as Package;
if (temp == null)
return false;
return this.Equals(temp);
}
public override string ToString()
{
return string.Format("PackageName: {0}, Version: {1}", PackageName, Version);
}
public int CompareTo(object obj)
{
if (obj == null)
return 1;
if (obj != null)
return (Equals(obj) ? -1 : 1);
else
throw new ArgumentException("Object is not a Temperature");
}
每当我在SortedDictionary上执行Contains或ContainsKey时,即使名称和版本相同,它也不起作用.
if (nugetPackagesInfo.Keys.Any(p => p.Equals(package)))
{
//List<string> currPackage;
//nugetPackagesInfo.TryGetValue(package, out currPackage);
if (!nugetPackagesInfo[package].Contains(packageFile))
{
nugetPackagesInfo[package].Add(packageFile);
}
nuGetPackagesInfo是我的字典对象. Any返回true.但是一旦传递并到达nugetPackagesInfo [package],则它将引发KeyNotFoundException.你能帮我弄清楚吗?我的CompareTo不正确吗?
解决方法:
将CompareTo和GetHashCode更改为这些实现.
public int CompareTo(object obj)
{
if (obj == null)
return 1;
return this.ToString().CompareTo(obj.ToString());
}
public override int GetHashCode()
{
unchecked
{
return ((PackageName != null ? PackageName.GetHashCode() : 0)*397) ^ (Version != null ? Version.GetHashCode() : 0);
}
}
public override string ToString()
{
return string.Format("PackageName: {0}, Version: {1}", PackageName??"", Version ?? "");
}
CompareTo-参见documentation.通过使用ToString(),您可以对程序包名称和版本进行比较,而不必自己进行检查.只需确保ToString是正确的即可(我添加了null检查,因此它不会引发Exception).
GetHashCode-不确定从何处获得实现.您需要确保该项目的哈希码始终是唯一的,除非它们确实相等.这是I found on this previous answer on SO的实现,请参见答案中的最后一个编辑.
标签:compareto,sorteddictionary,c 来源: https://codeday.me/bug/20191027/1942807.html