我定义了一个结构,用来作SortedList<T,K>的Key值,结构如下:
public struct S:IComparable<S>
{
public int X; public override bool Equals(object obj)
{
if (!(obj is S))
return false;
S oth = (S)obj;
return oth.X==X;
} public override int GetHashCode()
{
return X.GetHashCode();
} public int CompareTo(S other)
{
if (this.Equals(other))
return 0;
return 1;
} }
然后我这样调用: SortedList<S, int> list = new SortedList<S, int>();
S s1 = new S() { X = 40 };
S s2 = new S() { X = 150};
list.Add(s1,1);
list.Add(s2,1); bool b = list.ContainsKey(s1);
发现b的值居然为False,也就是说找不到Key,但这个Key明明是存在的。而且我已经重写了GetHashCode和Equals方法。
public struct S:IComparable<S>
{
public int X; public override bool Equals(object obj)
{
if (!(obj is S))
return false;
S oth = (S)obj;
return oth.X==X;
} public override int GetHashCode()
{
return X.GetHashCode();
} public int CompareTo(S other)
{
if (this.Equals(other))
return 0;
return 1;
} }
然后我这样调用: SortedList<S, int> list = new SortedList<S, int>();
S s1 = new S() { X = 40 };
S s2 = new S() { X = 150};
list.Add(s1,1);
list.Add(s2,1); bool b = list.ContainsKey(s1);
发现b的值居然为False,也就是说找不到Key,但这个Key明明是存在的。而且我已经重写了GetHashCode和Equals方法。
如果执行bool b = list.ContainsKey(s2);
则b为true。。
SortedList<S, int> list = new SortedList<S, int>();
S s0 = new S();
s0.X = 0;
S s1 = new S();
s1.X = 1;
S s2 = new S();
s2.X = 2;
S s3 = new S();
s3.X = 3;
list.Add(s0, 0);
list.Add(s1, 1);
list.Add(s2, 2);
list.Add(s3, 3);
如执行上面的代码 则
list.ContainsKey(s0);
false
list.ContainsKey(s1);
false
list.ContainsKey(s2);
true
list.ContainsKey(s3);
true
public int CompareTo(S other)
{
if (this.Equals(other))
return 0;
if (this.X < other.X)
{
return -1;
}
else
{
return 1;
}
}
按照我的理解,比较器至少返回三个值吧,-1,0,1分别是小于,等于,大于,楼主只返回了1,或许对于SortedList的排序来说,是有问题的。
楼主的代码换成Dictionary倒是没有问题。
CompareTo方法 怎么只有两个返回值?
这样排序的时候出错
SortedList执行ContainsKey的时候会依照排序进行比较 排序错了 比较的时候会省略掉后面的key不去比