我很确定我的问题来自一个非常愚蠢的错误,但我找不到它......
我使用自定义类作为 SortedList 中的键(我也尝试过 SortedDictionary)。
添加第一个项目没有问题,但是当我尝试添加第二个 Item ContainsKey() 时返回 true。
我用作键的类覆盖了 Equals() 和 GetHashCode()。
我检查了实际比较的项目,这就是我发现的:
手动调用 Equals() 来比较两个项目工作得很好,但是当它通过 ContainsKey 调用时,对象会将自身与自身的相同或另一个实例进行比较。我确保检查要添加的对象是否确实是一个新对象,并且它是...
这是 Key-Class
using System;
using System.Collections;
using System.Collections.Generic;
using TFVR.Components.Gaia.Content.Element;
using UnityEngine;
namespace TFVR.Components.Gaia.Content.QueueUi
{
public class QueueEntryElement : IComparable
{
public string Created;
public string ProductId;
public ContactInformationElement ContactInformation;
public int Priority;
public string OrderId;
public QueueEntryElement(string created, string productId
, ContactInformationElement contactInformation, int priority
, string orderId)
{
Created = created;
ProductId = productId;
ContactInformation = contactInformation;
Priority = priority;
OrderId = orderId;
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
QueueEntryElement otherQueueEntryElement = obj as QueueEntryElement;
if (otherQueueEntryElement != null)
return this.Priority.CompareTo(otherQueueEntryElement.Priority);
else
throw new ArgumentException("Object is not a QueueEntryElement");
}
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
QueueEntryElement e = (QueueEntryElement)obj;
return (this.OrderId == e.OrderId);
}
}
public override int GetHashCode()
{
return OrderId.GetHashCode();
}
public override string ToString()
{
string str = "Created: "
+ Created + ", "
+ "Product Id: "
+ ProductId + ", "
+ "Contact Information: "
+ "{" + ContactInformation + "}" + ", "
+ "Priority: "
+ Priority + ", "
+ "Order Id: "
+ OrderId;
return str;
}
}
}
这是我尝试添加到 SortedList 的代码
SortedList<QueueEntryElement, string> dict = new SortedList<QueueEntryElement, string>();
private void add(QueueEntryElement q, string
{
if (!dict.ContainsKey(q))
{
dict.Add(q, s);
}
}
ContactInformationElement c1 = new ContactInformationElement("a","b","c","d","e");
QueueEntryElement e1 = new QueueEntryElement("a","b", c1, 0,"123");
ContactInformationElement c2 = new ContactInformationElement("f", "g", "h", "i", "j");
QueueEntryElement e2 = new QueueEntryElement("c", "d", c2, 0, "234");
add(e1,"one");
add(e2,"two");
最佳答案
这里的问题是 SortedList.ContainsKey 使用 CompareTo... NOT Equals 来确定存在。
这意味着您基本上使用 Priority 作为 Key NOT OrderId。
因此,就您的示例而言,实际的关键是优先级。
因此,如果您的项目没有唯一的优先级值,那么它们将不会被添加到“字典”中。
这是 C# Generic SortedList 的正常行为。
关于一旦项目在集合中,C# ContainsKey 返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868023/