C#的列表框中没有看到我的overrided sort()方法我的、框中、方法、列表

2023-09-04 04:38:02 作者:﹌ 泪※如雨﹌

我想重写排序()在我的自定义控制方法。当我的控件包含列表框,然后我重写sort()方法,一切正常。

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

但是,当我希望我的列表框的(1)由另一个列表框延长(2),包含sort()方法,然后添加列表框(1)以我的用户,然后将其排序过,但没有使用我的sort()方法(好像它并没有看到我的排序(),从列表框类只是正常排序())。

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).

我的列表框的(2)包含code:

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?

推荐答案

如果你打电话给你的排序,它可能是必要投你的列表框到您的自定义列表框的类型(如果它是在基本型)使用您的排序指定方法。

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

您必须使用被覆盖的列表框,其正确的类型,我的意思是把它作为MyListBox而不是列表框。不要害怕,你需要实现所有其他方法,你重写现有的类,而不是一个接口。您可以使用所有必要的基础方法。

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.