Nat*_*n W 12 c# oop inheritance
我不确定如何标题这个问题,但基本上我有这样的界面:
public interface IFoo
{
string ToCMD();
}
Run Code Online (Sandbox Code Playgroud)
一些实现IFoo的absract类如:
public abstract class Foo : IFoo
{
public abstract string ToCMD();
}
public abstract class Bar : IFoo
{
public abstract string ToCMD();
}
Run Code Online (Sandbox Code Playgroud)
那么继承Foo和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.
Run Code Online (Sandbox Code Playgroud)
我这样做是为了当我有自定义列表时:
public class Store<T> : List<T> where T : IFoo {}
Run Code Online (Sandbox Code Playgroud)
然后,我可以限制其中的类型,但通过使用接口,它仍将采用任何类型的IFoo.
就像是:
Store<Foo> store = new Store<Foo>(); //Only Foo types will work.
store.Add(new FooClass1()); //Will compile.
Store<IFoo> store = new Store<IFoo>(); //All IFoo types will work.
store.Add(new FooClass1()); //Will compile.
store.Add(new BarClass()); //Will compile.
Run Code Online (Sandbox Code Playgroud)
我的问题是:这是否可以解决这个问题?或者,还有更好的方法?
编辑:图片 - >

一般而言,对继承链的需求是值得怀疑的.
然而,将抽象基类与接口相结合的具体方案......我这样看:
如果你有这样的抽象基类,你也应该有一个相应的接口.如果您有一个接口,那么只在继承链合理的地方使用抽象基类.
也就是说,如果我正在编写一个库,这是我的API/Framework的一部分,我通常会包含一个可以用作基类的"默认实现".它将尽可能以一种天真的,通用的方式实现接口方法,并让其余的继承者根据需要实现/覆盖.
这只是图书馆的一个便利功能,通过提供可能涵盖他们需要实施的大部分功能的示例来帮助想要实现界面的人.
简而言之,接口比基类更有价值,但基类可能会节省大量时间并减少错误的接口实现.
| 归档时间: |
|
| 查看次数: |
12956 次 |
| 最近记录: |