0

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

这是代码:

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);
    }
}
4

1 回答 1

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);
    }
}
于 2010-02-11T07:16:19.017 回答