我定义了一个结构,用来作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方法。

解决方案 »

  1.   

    也许你会说,需要重写ContainsKey方法,但我认为既然我提供了GetHashCode的方法,它就应该帮我历遍list里的值,然后调用GetHashCode,找出Key是否存在
      

  2.   

    发现一个有趣的现象  
    如果执行bool b = list.ContainsKey(s2); 
    则b为true。。
      

  3.   


     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
      

  4.   

    这个我早就发现了,这是因为它没有历遍list集合,而是只检测了第一条记录。
      

  5.   

    把CompareTo方法改成这样
                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倒是没有问题。
      

  6.   

    SortedList的ContainsKey方法并没有去调用GetHashCode的方法,我猜想是因为SortedList本身就是个排序列表,而并不需要去调用了吧。
      

  7.   

    找到原因了。
    CompareTo方法 怎么只有两个返回值?
    这样排序的时候出错 
    SortedList执行ContainsKey的时候会依照排序进行比较 排序错了 比较的时候会省略掉后面的key不去比