C# 包含键在项位于集合中后返回 true



我很确定我的问题来自一个非常愚蠢的错误,但我找不到它......

我正在使用自定义类作为排序列表中的键(我也尝试过排序词典(。 第一个项目被添加没有问题,但是当我尝试添加第二个项目时,ContainsKey(( 返回 true。

我用作键的类覆盖了 Equals(( 和 GetHashCode((。 我检查了实际比较的项目,这就是我发现的: 手动调用 Equals(( 来比较两个项目就可以了,但是当通过 ContainsKey 调用它时,对象会将自身与自身的相同或另一个实例进行比较。我确保检查要添加的对象是否确实是新对象,它是......

这是密钥类

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<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...不等于确定存在。

这意味着您基本上使用优先级作为键而不是订单ID。

因此,就您的示例而言,实际键是优先级。

因此,如果您的项目没有唯一的优先级值,则它们将不会添加到"字典"中。

这是 C# 泛型排序列表的正常行为。

我添加了一些虚拟代码,以防有人仍然对测试感兴趣。为了解决我的问题,我只是将我的 CompareTo(( 更改为:

public int CompareTo(QueueEntryElement obj)
{
if (obj == null) return 1;
QueueEntryElement otherQueueEntryElement = obj as QueueEntryElement;
if (otherQueueEntryElement != null)
{
if (Priority.CompareTo(otherQueueEntryElement.Priority) == 0)
{
return OrderId.CompareTo(otherQueueEntryElement.OrderId);
}
return 0;
}
else
throw new ArgumentException("Object is not a QueueEntryElement");
}

最新更新