使用Interface +抽象类进行inheritance设计。 好的做法?

我不确定如何标题这个问题,但基本上我有这样的界面:

public interface IFoo { string ToCMD(); } 

几个实现IFoo的absract类:

 public abstract class Foo : IFoo { public abstract string ToCMD(); } public abstract class Bar : IFoo { public abstract string ToCMD(); } 

那么inheritanceFoo和Bar的类:

 public class FooClass1 : Foo { public override string ToCMD() {return "Test";} } ///there are about 10 foo classes. public class BarClass : Bar { public override string ToCMD() {return "BarClass";} } ///about the same for bar classes. 

我这样做,所以当我有我的自定义列表,如:

 public class Store : List where T : IFoo {} 

然后,我可以限制其中的类型,但通过使用接口,它仍将采用任何类型的IFoo。

就像是:

 Store store = new Store(); //Only Foo types will work. store.Add(new FooClass1()); //Will compile. Store store = new Store(); //All IFoo types will work. store.Add(new FooClass1()); //Will compile. store.Add(new BarClass()); //Will compile. 

我的问题是:这是一个可行的方法吗? 或者,还有更好的方法?

编辑:图片 – > 替代文字

一般而言,对inheritance链的需求是值得怀疑的。

然而,将抽象基类与接口相结合的具体方案……我这样看:

如果你有这样的抽象基类,你也应该有一个相应的接口。 如果你有一个接口,那么只在inheritance链合理的地方使用抽象基类。

也就是说,如果我正在编写一个库,这是我的API / Framework的一部分,我通常会包含一个可以用作基类的“默认实现”。 它将尽可能以一种天真的,通用的方式实现接口方法,并让其余的inheritance者根据需要实现/覆盖。

这只是图书馆的一个便利function,通过提供可能涵盖他们需要实施的大部分function的示例来帮助想要实现界面的人。

简而言之,接口比基类更有价值,但基类可能会节省大量时间并减少错误的接口实现。

那么,这就是where关键字的用途。 您可能需要评估对象模型以确保inheritance的深度是必要的。 深层inheritance层次结构往往使项目复杂化并且通常是一个红旗,但它取决于具体情况。

通常,您不需要抽象类来提取您正在与列表讨论的function,并且接口是指定类型限制的“首选”方法。 如果您想要封装常用function,我只会使用您的类的抽象版本。

简短的回答 :确保你不会inheritance疯狂。

希望有所帮助!

你也可以使用接口。 没有理由使用抽象类。

 public interface Foo : IFoo { } public interface Bar : IFoo { } 

你需要界面; 你可能需要也可能不需要抽象类。

一般来说,如果你可以在基类中提供一些有用的行为,那么提供一个基类; 如果基类本身不完整,则将其设为抽象(用VB语言中的MustInherit)

否则,界面就足够了

我不太确定这是否是您正在寻找的,但也许您想要做的是将所有界面全部废弃并执行此操作:

 abstract class Base { public abstract string ToCMD(); } abstract class Foo : Base { } abstract class Bar : Base { } 

希望你在FooBar课程中有其他成员! 这将允许您通过Base限制自定义集合,或者只使用普通的List