c# - 基类实现接口(interface)

标签 c# .net oop

  1. 基类实现接口(interface)有哪些缺点/风险?
  2. 始终在子类上实现接口(interface)是否更好?
  3. 您什么时候会使用其中之一?

    public interface IFriendly
    {
        string GetFriendly();
    }
    
    
    public abstract class Person: IFriendly
    {
        public abstract string GetFriendly(); 
    }
    

    对比

    public interface IFriendly
    {
        string GetFriendly();
    }
    
    public abstract class Person
    {
       // some other stuff i would like subclasses to have
    }
    
    public abstract class Employee : Person, IFriendly
    {
        public string GetFriendly()
        {
            return "friendly";
        }
    }
    

最佳答案

嗯,你需要这样想:

public interface IBreathing
{
    void Breathe();
}

//because every human breathe
public abstract class Human : IBreathing
{
    abstract void Breathe();
}

public interface IVillain
{
    void FightHumanity();
}

public interface IHero
{
    void SaveHumanity();
}

//not every human is a villain
public class HumanVillain : Human, IVillain
{
    void Breathe() {}
    void FightHumanity() {}
}

//but not every is a hero either
public class HumanHero : Human, IHero
{
    void Breathe() {}
    void SaveHumanity() {}
}

重点是你的基类应该实现接口(interface)(或者继承但只将其定义公开为抽象)只有当从它派生的每个其他类也应该实现该接口(interface)时。 因此,通过上面提供的基本示例,您可以让 Human 仅在每个 Human 呼吸(这里是正确的)时实现 IBreathing

但是!您不能让 Human 同时实现 IVillainIHero,因为这会让我们以后无法区分它是一个还是另一个。实际上,这样的实现意味着每个 Human 既是反派又是英雄。

总结您问题的答案:

  1. 基类实现接口(interface)有哪些缺点/风险?

    没有,如果从它派生的每个类也应该实现该接口(interface)。

  2. 始终在子类上实现接口(interface)是否更好?

    如果从基类派生的每个类也应该实现该接口(interface),那是必须

  3. 您什么时候会使用其中之一?

    如果从基类派生的每个类都应该实现这样的接口(interface),则让基类继承它。如果没有,让具体类实现这样的接口(interface)。

关于c# - 基类实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376393/

相关文章:

java - 我如何用 int 数组编写获胜方法

PHP 用变量声明类

vb.net - 将函数声明为私有(private)与公有之间有什么实际区别?

c# - 在派生类中转换接口(interface)属性

c# - 如何在 PropertyGrid 中动态显示或隐藏属性?

c# - 为什么 WCF 在遇到 302 响应时无法调用 SOAP 服务?

C# 与数据库代码简化

c# - Visual Studio 2010 : Why can't I resume an application when I made changes in a delegate?

c# - NHibernate,使用带有 Future 的 QueryOver 获取孙子集合

c# - mongoDB upsert 数组