尝试使用SortedDictionary扩展方法时获取异常......为什么?

时间:2010-05-10 20:13:43

标签: c# .net comparison

我正在尝试将自定义对象放入已排序的字典中......然后我尝试在此排序字典上使用扩展方法(Max())。但是,我得到了例外:“至少有一个对象必须实现IComparable”。我不明白为什么我会这样做,因为我的自定义对象显然实现了IComparable。这是我的代码:

public class MyDate : IComparable<MyDate>
{
    int IComparable<MyDate>.CompareTo(MyDate obj)
    {
        if (obj != null)
        {
            if (this.Value.Ticks < obj.Value.Ticks)
            {
                return 1;
            }
            else if (this.Value.Ticks == obj.Value.Ticks)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }
    }

    public MyDate(DateTime date)
    {
        this.Value = date;
    }

    public DateTime Value;
}


class Program
{
    static void Main(string[] args)
    {
        SortedDictionary<MyDate, int> sd = new SortedDictionary<MyDate,int>();

        sd.Add(new MyDate(new DateTime(1)), 1);
        sd.Add(new MyDate(new DateTime(2)), 2);

       Console.WriteLine(sd.Max().Value);   // Throws exception!!  
    }
}

我到底在做什么?

1 个答案:

答案 0 :(得分:1)

这是因为这并不是要比较你的自定义对象,而是KeyValuePair的实例。

这应该有效

Console.WriteLine(sd.Last().Value);   

因为排序的字典是排序的,所以假设比较器将最小值与最大值进行比较,最后一项是最大的。