基类实现接口

鲍勃·斯旺森
  1. 基类实现接口的缺点/风险是什么?
  2. 始终在子类上实现接口是否更好?
  3. 您何时会使用其中一个?

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

    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";
        }
    }
    
姆维琴斯基

好吧,您需要这样考虑:

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() {}
}

关键是,只有从其派生的所有其他类也都应实现该接口时,基类才应实现该接口(或继承但仅将其定义公开为抽象)。因此,使用上面提供的基本示例,仅在每次呼吸时才Human执行工具(在这里是正确的)。IBreathingHuman

但!您不能同时Human实现这两种工具IVillainIHero因为这将使我们以后无法区分它是另一个还是另一个。实际上,这样的实施意味着每个人Human都是恶棍和英雄。

总结问题的答案:

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

    无,如果派生自该类的每个类也应实现该接口。

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

    如果每个派生自基类的类也都应实现该接口,则必须

  3. 您何时会使用其中一个?

    如果每个派生自基类的类都应实现这样的接口,则使基类继承它。如果不是,则使具体类实现这样的接口。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章