简体   繁体   中英

How to have an abstract class require an interface to be implemented by descendant classes?

I want to make an abstract class that imposes a restriction that its child classes must implement an interface. I want to avoid having to implement the interface class in the abstract class. The code below won't do what I'd like. Does anyone have a suggestion of what I could do?

public interface IItem()
{
     bool IsUsable();
}

public abstract class Item : IItem
{
    MemberVar var;
    public void DoSomething()
    {
        //Do something
    }
}

public class Something : Item
{
     public bool IsUsable()
     {
         return true;
     }
}

Just make the method abstract in your abstract class :

public abstract class Item : IItem
{
    //...

    public abstract bool IsUsable();
}

In the classes that inherit the Item class use the override keyword :

public override bool IsUsable()
{
    // Do stuff
}

The overriding implementations stubs can be automatically added by VS by right-clicking on the parent abstract class and selecting Implement Abstract Class :

在此输入图像描述

使用抽象方法和/或属性实现基类中的接口

Simply add abstract keyword to every method/properties that the interface requires to implement.

For instance, this is how the DoSomething() method should look:

public abstract void DoSomething();

This way the derived classes will have to implement the interface themselves.

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