简体   繁体   中英

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.
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).
Then i've created a class that inherits from TableLayoutPanel and implements the interface.
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. In this case, the TableLayoutPanel, but i wanted to use the instance itself...
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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