SortedDictionary ContainsKey方法错了吗?

时间:2012-03-20 07:49:34

标签: c# dictionary enums comparable

所以基本上我有这样的事情:

private SortedDictionary<Priority, List<String>> example = new SortedDictionary<Priority, List<String>>(new PriorityComparer());

public void Submit(Priority priority, String test)
{
    if (!example.ContainsKey(priority))
    {
        example.Add(priority, new List<String> { test });
        // adds an entry with the key (Priority.Low) twice, why?
    }
    else
    {
        example[priority].Add(test); // never called
    }
}

仅提交一堆测试元素:

Submit(Priority.Critical, "test4");
Submit(Priority.Low, "test");
Submit(Priority.Normal, "test3");
Submit(Priority.Low, "test2");

优先级只是一个枚举,优先级从低(0)到严重(10)。这只是一个典型的枚举,没什么特别的。

优先级比较器:

public class PriorityComparer : IComparer<Priority>
{
    public int Compare(Priority x, Priority y)
    {
        if (x > y)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
}

1 个答案:

答案 0 :(得分:9)

您的比较实施不完整。当x == y(返回0)时,你会错过这种情况。