如何重写SortedList添加方法以按值排序 [英] How to override SortedList Add method for sorting by value

查看:307
本文介绍了如何重写SortedList添加方法以按值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a SortedList in my code. I fill inside it key value pairs. When I add an item to SortedList it sorts automatically by key. But i need to sort it by value. Because the values are visible texts in a combobox. They must be alphabetically sorted. I decided to write a class and inherit from SortedList class and override the Add method.

但是当我查看

But when I looked at the code of Microsoft's SortedList class, I see there is an Insert method and it makes the sorting and unfortunately it is private so I cannot override it. Can you help me about this?

注意:我不能使用ArrayListDictionary或其他名称.我无法管理项目中的所有代码.我必须返回从SortedList

Note: I cant use ArrayList or Dictionary or something else. I cannot manage all code in our project. I have to return 'SortedList' or 'MySortedList' derived from SortedList

推荐答案

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

My first suggestion was to use a custom comparer but his didn't solve the problem. I therefore investigated SortedList implementaion more detailed and replaced my original post with the following suggestion:

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

Overriding the Add method and invoke the private Insert using reflection should do the trick

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

这篇关于如何重写SortedList添加方法以按值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆