是否可以为继承基类的成员提供实现该接口(interface)的接口(interface)。
一些接口(interface)
public interface ICanWork
{
void DoSomething();
}
一些抽象类
public abstract Class MyBase : ICanWork
{
// I do not want to implement the ICanWork but instead want the derived class which inherit it
}
继承基类的类
public class House : MyBase
{
// i want the compiler to know that it needs to implement ICanWork
}
这并没有像我预期的那样工作。
难道只有把Interface放在Class上继承基类才能实现吗?
例如
public class House : MyBase, ICanWork
{
}
有什么有用的建议吗?
最佳答案
您必须在实现您的接口(interface)的类中实现接口(interface),即使您的类是抽象
。但是,您可以使该方法的实现也抽象
,这会强制所有派生类实现它:
public abstract Class MyBase : ICanWork
{
public abstract void DoSomething();
}
当您现在定义一个派生您的 asbtract 基类的类时,您还必须实现该方法:
public class House : MyBase
{
public override void DoSomething() { ... }
}
来自 MSDN :
Like a non-abstract class, an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. However, an abstract class is permitted to map interface methods onto abstract methods
关于c#接口(interface),抽象类,强制继承类不是抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44721350/