0

我的代码中有一个SortedList。我在里面填写键值对。当我添加一个项目时,SortedList它会自动按键排序。但我需要按价值对其进行排序。因为这些值是组合框中的可见文本。它们必须按字母顺序排序。我决定编写一个类并从SortedList类继承并覆盖该Add方法。

但是当我查看Microsoft 的 SortedList 类的代码时,我看到有一个Insert方法可以进行排序,不幸的是它是私有的,所以我无法覆盖它。你能帮我解决这个问题吗?

注意:我不能使用ArrayListorDictionary或其他东西。我无法管理我们项目中的所有代码。我必须返回 ' SortedList' 或 ' MySortedList' 派生自SortedList

4

1 回答 1

2

我的第一个建议是使用自定义比较器,但他没有解决问题。因此,我更详细地调查了 SortedList 的实现,并用以下建议替换了我原来的帖子:

覆盖 Add 方法并使用反射调用私有 Insert 应该可以解决问题

private MySortedList()
{
}

public override void Add(object key, object value)
{
    if (key == null || value == null)
    {
        //throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key"));
        throw new ArgumentNullException(); // build your own exception, Environment.GetResourceString is not accessible here
    }

    var valuesArray = new object[Values.Count];
    Values.CopyTo(valuesArray , 0);

    int index = Array.BinarySearch(valuesArray, 0, valuesArray.Length, value, _comparer);
    if (index >= 0)
    {
        //throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", new object[] { this.GetKey(index), key }));
        throw new ArgumentNullException(); // build your own exception, Environment.GetResourceString is not accessible here
    }

    MethodInfo m = typeof(SortedList).GetMethod("Insert", BindingFlags.NonPublic | BindingFlags.Instance);
    m.Invoke(this, new object[] {~index, key, value});
}
于 2012-11-16T10:49:01.077 回答