How to override SortedList Add method for sorting by value

試著忘記壹切 提交于 2019-12-11 19:15:43

问题


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?

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


回答1:


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:

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


来源:https://stackoverflow.com/questions/13414564/how-to-override-sortedlist-add-method-for-sorting-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!