C#'s ListBox doesn't see my overrided Sort() method

一世执手 提交于 2020-01-03 03:57:09

问题


I'm trying to override Sort() method in my custom control. When my control contains ListBox and then I override Sort() method, everything works.

But when I want my ListBox (1) to be extended by another ListBox (2), that contains Sort() method, and then add that ListBox (1) to my UserControl, then it sorts too, but isn't using my Sort() method (seems like it doesn't see my Sort(), just normal Sort() from ListBox class).

My ListBox (2) contains code:

//...
public class MyListBox: ListBox
{
    public MyListBox
    {    
        this.Sorted = true;
    }
    // more methods
    override protected void Sort() 
    {
        // sorting code
    }
}
//...

And my custom control looks like:

//...
public partial class MyControl: UserControl
{
    public MyControl()
    {
        InitializeComponent(); // method in MyControl.Designer.cs (myListBox1 is declared in that class)
    }
    // more methods
    public ListBox.ObjectCollection Item //that's because I want my control to behavior like ListBox instead of creating void AddItem(Object) method, etc...
    {
        get { return myListBox1.Items; }
    }
}        

so I think everything should work, but it doesn't... Any ideas?


回答1:


If you call your Sort, it could be necessary to cast your ListBox to your custom ListBox type (if it is in the base type) to use your specified Sort method.

((MyListBox)myList).Sort();

you must use your overriden ListBox with its correct type, I mean use it as MyListBox and not as ListBox. Don't be afraid that you need to implement all the other methods, you're overriding an existing class and not an interface. you can use all the needed base methods.




回答2:


If I understand this correctly myListBox1 is of type ListBox not of type MyListBox which is why your Sort isn't being called.



来源:https://stackoverflow.com/questions/6161117/cs-listbox-doesnt-see-my-overrided-sort-method

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