简体   繁体   English

如何从控件类和抽象类继承?

[英]How can I inherit from a control class and an abstract class?

I have a class with a method that accepts an argument which must be a Control with expected methods. 我有一个带有接受参数的方法的类,该参数必须是具有预期方法的Control。
I've created an interface with those methods. 我已经用这些方法创建了一个接口。
I've created an abstract class that inherits from Control and implements the interface putting all methods abstract (this is the type of my argument above). 我创建了一个抽象类,该类继承自Control,并实现了将所有方法抽象的接口(这是我上面的参数的类型)。
Then i've created a class that inherits from TableLayoutPanel and implements the interface. 然后,我创建了一个继承自TableLayoutPanel的类并实现了该接口。
I create an instance of this class but then i cannot use it as the argument. 我创建了此类的实例,但随后我无法将其用作参数。
I know why. 我知道为什么。 But what is the workaround? 但是,解决方法是什么? I know i could add a method to the interface that returns the Control instance. 我知道我可以在返回Control实例的接口中添加一个方法。 In this case, the TableLayoutPanel, but i wanted to use the instance itself... 在这种情况下,是TableLayoutPanel,但是我想使用实例本身...
Also, i don't want to make casts inside the method that receives the argument, it has to be "compile-time/type safe" to use in a library for example... 另外,我不想在接收参数的方法内部进行强制类型转换,例如在库中使用时必须“编译时/类型安全” ...

class CollapsibleList : Panel
{
    public void AddItem(CollapsibleListItem item)
    {
        someContainer.Controls.Add(item);
        item.CollapsibleListItemCollapse();
    }    
}

public interface ICollapsibleListItem
{
    string CollapsibleListItemName { get; }
    void CollapsibleListItemCollapse();
    void CollapsibleListItemExpand();
}

public abstract class CollapsibleListItem : Control, ICollapsibleListItem
{
    public abstract string CollapsibleListItemName { get; }
    public abstract void CollapsibleListItemCollapse();
    public abstract void CollapsibleListItemExpand();
}

class ListBoxCollapsibleListItem : TableLayoutPanel, ICollapsibleListItem
{
    //... implemented interface methods
}

class Main
{
    public void SomeMethod()
    {
        var item = new ListBoxCollapsibleListItem();
        var collapsibleList = new CollapsibleList();
        collapsibleList.AddItem(item as CollapsibleListItem); //cast error!
    }
}

try below, 试试下面,

collapsibleList.AddItem(item as ICollapsibleListItem); collapsibleList.AddItem(item为ICollapsibleListItem);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM