基类实现接口

Bob*_*son 4 .net c# oop

  1. 基类实现接口的缺点/风险是什么?
  2. 总是在子类上实现接口更好吗?
  3. 你什么时候使用其中一个?

    public interface IFriendly
    {
        string GetFriendly();
    }
    
    
    public abstract class Person: IFriendly
    {
        public abstract string GetFriendly(); 
    }
    
    Run Code Online (Sandbox Code Playgroud)

    VS.

    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";
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

mwi*_*ski 9

好吧,你需要这样想:

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() {}
}
Run Code Online (Sandbox Code Playgroud)

关键是你的基类应该实现接口(或继承,但只将它的定义暴露为抽象),只有从它派生的每个其他类也应该实现该接口.因此,通过上面提供的基本示例,您只能在每次呼吸时制作Human器具(这里是正确的).IBreathingHuman

但!你不能同时制造Human工具IVillain,IHero因为这将使我们以后无法区分它是否是一个或另一个.实际上,这样的实施意味着每个人Human都同时是恶棍和英雄.

要结束你的问题的答案:

  1. 基类实现接口的缺点/风险是什么?

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

  2. 总是在子类上实现接口更好吗?

    如果从基础派生的每个类都应该实现该接口,那么它是必须的

  3. 你什么时候使用其中一个?

    如果从基类派生的每个类都应该实现这样的接口,那么make base class继承它.如果没有,请使具体类实现这样的接口.