比较通用类中的嵌套内部类

时间:2010-02-11 06:39:15

标签: c# generics icomparable

我正在制作泛型类中的嵌套内部类,我不确定我是否正确地写了这个。这里有什么明显的错误吗?

以下是代码:

public class Foo<T> where T : IComparable<T>
{
    protected class Bar : IComparable
    {
        private KeyValuePair<T, string> _keyval;

        public Bar(KeyValuePair<T, string> kv)
        {
            _keyval = kv;
        }

        public int CompareTo(object obj)
        {
            T comparing = (T)obj;
            return _keyval.Key.CompareTo(comparing.key);
        }
    }

    private List<Bar> _bars;

    public Foo()
    {
        _bars = new List<Bar>();
    }

    public void AddKeyValInOrder(KeyValuePair<T, string> kv)
    {
        Bar toAdd = new Bar(kv);

        int positionToAddAt = _bars.BinarySearch(toAdd);
        if (positionToAddAt < 0)
            positionToAddAt = positionToAddAt ^ -1;

        _bars.Insert(positionToAddAt, toAdd);
    }
}

1 个答案:

答案 0 :(得分:2)

首先请注意,如果您不需要重复,SortedList<T>可能会有所帮助。

List<Bar>想要比较Bar个实例,因此您的比较需要适用于Bar(最容易通过实施IComparable<Bar>来强制执行:

protected class Bar : IComparable, IComparable<Bar>
{
    private KeyValuePair<T, string> _keyval;

    public Bar(KeyValuePair<T, string> kv)
    {
        _keyval = kv;
    }
    public int CompareTo(Bar other)
    {
        return _keyval.Key.CompareTo(other._keyval.Key);
    }
    int IComparable.CompareTo(object obj)
    {
        return CompareTo(obj as Bar);
    }
}