C#'s ListBox doesn't see my overrided Sort

2019-05-29 09:15发布

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?

2条回答
叼着烟拽天下
2楼-- · 2019-05-29 09:54

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.

查看更多
Evening l夕情丶
3楼-- · 2019-05-29 09:54

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

查看更多
登录 后发表回答