- 基类实现接口(interface)有哪些缺点/风险?
- 始终在子类上实现接口(interface)是否更好?
您什么时候会使用其中之一?
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
同时实现 IVillain
和 IHero
,因为这会让我们以后无法区分它是一个还是另一个。实际上,这样的实现意味着每个 Human
既是反派又是英雄。
总结您问题的答案:
基类实现接口(interface)有哪些缺点/风险?
没有,如果从它派生的每个类也应该实现该接口(interface)。
始终在子类上实现接口(interface)是否更好?
如果从基类派生的每个类也应该实现该接口(interface),那是必须
您什么时候会使用其中之一?
如果从基类派生的每个类都应该实现这样的接口(interface),则让基类继承它。如果没有,让具体类实现这样的接口(interface)。
关于c# - 基类实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376393/