c#接口(interface),抽象类,强制继承类不是抽象类

标签 c# .net oop inheritance interface

是否可以为继承基类的成员提供实现该接口(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/

相关文章:

c# - Visual Studio 无法附加到 Unity,为什么?

c# - 为什么我需要将空合并运算符放在方括号中?

.net - 保护配置问题中的密码

c# - 对于多条消息和成功/失败,是否有替代通知模式的方法?

java - Java 国际象棋——面向对象与效率

class - C++ 从不同类访问一个类中函数中的变量

c# - (Excel 互操作)如何将一个工作表复制到 VSTO 中的另一个工作簿?

c# - Migradoc 添加水平线

c# - 在 .NET COM 互操作中传递强类型参数

c# - LINQ: "select new {e.FName, e.LName}"和 "select (e.FName, e.LName)"之间的区别?