gpt4 book ai didi

c# - 在 C# 中从已排序的字典中获取数据时出错

转载 作者:行者123 更新时间:2023-11-30 15:22:15 25 4
gpt4 key购买 nike

我有一个 SortedDictionary<Package, List<string>> .以下是包类:

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");
}

每当我做 ContainsContainsKeySortedDictionary 上,即使名称和版本相同,它也不起作用。

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虽然返回真。但是一旦通过并到达nugetPackagesInfo[package] , 然后它抛出 KeyNotFoundException .你能帮我弄清楚吗?是我的CompareTo不正确?

最佳答案

CompareTo 的实现似乎不正确。事实上,您没有实现包的任何排序。您很可能应该按名称订购包,如果相同则按版本订购。

Package.CompareTo 的核心应该如下所示(简化;不考虑 other == null):

// try name ordering
int nameOrdering = this.Name.CompareTo(other.Name);

// names not equal ⇒ ordering is clear and no need to inspect further
if (nameOrdering != 0)
{
return nameOrdering;
}
// names are equal ⇒ resort to version ordering
else
{
return this.Version.CompareTo(other.Version);
}

你还应该 read the documentation for String.CompareTo()因为它具有特定于文化的语义。

关于c# - 在 C# 中从已排序的字典中获取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com