ArgumentException:元素已存在于 SortedSet 中

ArgumentException: element already exists in SortedSet

我在 C# 中使用 SortedList 时遇到一些问题(我正在使用 Visual Studio 2015 开发 Unity 5.0.3)。我有两个 classes ScoreKey 和 Score。 ScoreKey 实现 IComparable。

但是当我尝试向 SortedList 添加条目时出现错误

ArgumentException: element already exists
System.Collections.Generic.SortedList`2[ScoreKey,Score].PutImpl (.ScoreKey key, .Score value, Boolean overwrite)

我不明白为什么会出现此错误。我使用 class 的实例作为密钥,所以不可能有相同的密钥,对吗?这是代码。

Class 定义:

public class ScoreKey : IComparable
{
    public uint val;
    public uint timestamp;
    public int CompareTo(object obj)
    {
        ScoreKey s2 = obj as ScoreKey;
        if (s2.val == val)
        {
            return timestamp.CompareTo(s2.timestamp);
        }
        return val.CompareTo(s2.val);
    }
}
[System.Serializable]
public class Score
{

    public ScoreKey key;
    public uint val
    {
        get { return key.val; }
    }
    string user;
    public uint timestamp
    {
        get
        {
            return key.timestamp;
        }
    }
    public Score(string _user, uint _score)
    {
        key = new ScoreKey();
        key.timestamp = GetUTCTime();
        user = _user;
        key.val = _score;
    }
}

测试代码:

SortedList<ScoreKey, Score> scoreList = new SortedList<ScoreKey, Score>();
Score[] scores = {
    new Score("Bishal", 230),
    new Score("Bishal", 3456),
    new Score("Bishal", 230),
    new Score("Bishal", 123),
    new Score("Bishal", 86),
    new Score("Bishal", 4221)
};
for(int i = 0; i< scores.Length; i++)
{
    Debug.Log(scores[i].pretty);

    scoreList.Add(scores[i].key, scores[i]);
}

编辑:

**GetUTCTime 函数:**

public static uint GetUTCTime()
{
   return (uint)(System.DateTime.UtcNow.Subtract(new System.DateTime(1970, 1, 1))).TotalSeconds;
}

我不知道 GetUTCTime 方法有什么作用,但是,假设它 returns 当前时间的某种度量,它很可能 returns same value连续几次。

因此您将有一个重复键,因为第二个字段 val 在两个元素中为 230:

new Score("Bishal", 230),
new Score("Bishal", 3456),
new Score("Bishal", 230),

如果您不想像密钥那样生成唯一的时间戳,您可以检查 How to ensure a timestamp is always unique?