C# ArgumentException:元素已存在于SortedSet中
我在C#中使用SortedList时遇到一些问题(我正在使用Visual Studio 2015开发Unity 5.0.3)。我有两门课:ScoreKey和Score。ScoreKey实现了IComparable 但当我试图将条目添加到SortedList时,我得到了错误C# ArgumentException:元素已存在于SortedSet中,c#,sorting,unity3d,unity5,sortedlist,C#,Sorting,Unity3d,Unity5,Sortedlist,我在C#中使用SortedList时遇到一些问题(我正在使用Visual Studio 2015开发Unity 5.0.3)。我有两门课:ScoreKey和Score。ScoreKey实现了IComparable 但当我试图将条目添加到SortedList时,我得到了错误 ArgumentException: element already exists System.Collections.Generic.SortedList`2[ScoreKey,Score].PutImpl (.Score
ArgumentException: element already exists
System.Collections.Generic.SortedList`2[ScoreKey,Score].PutImpl (.ScoreKey key, .Score value, Boolean overwrite)
我不明白为什么我会犯这个错误。我使用一个类的实例作为键,所以不可能有相同的键,对吗?这是代码
类定义:
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]);
}
测试代码:
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
方法做什么,但是,假设它返回当前时间的某个度量值,那么它很有可能连续几次返回当前时间
因此,您将有一个重复的键,因为第二个字段val
在两个元素中为230:
new Score("Bishal", 230),
new Score("Bishal", 3456),
new Score("Bishal", 230),
如果您不想生成唯一的时间戳,您可以检查。我添加了getutctime方法定义。val将不为0检查分数类的构造函数在当前示例中,时间戳也不会被检查,因为没有一个分数为0equal@bytestorm从什么时候开始230不等于230?由于您正在将时间戳转换为整数值,如果两个对象是在同一秒内创建的,它们将具有相同的时间戳。@Dennis_E哦,很抱歉,这就是问题所在。我的错。是的,我需要让时间戳独一无二。这将解决其余的问题。