[英]Generics or not Generics
基本上我有一个包含不同水果的自定义List类。 假设每个水果都有一个存储在列表中的ID号。
有没有更好的:
new AppleList();
new OrangeList();
new LemonList();
要么
new FruitList<Fruit.Apple>();
new FruitList<Fruit.Orange>();
new FruitList<Fruit.Lemon>();
需要考虑的事项:
我想使用更清晰,更好的设计,更快,更高效等等。另外,如果以上2种技术不是最好的,请提出您的想法。
编辑:如果不清楚,顺便说一句水果是一个枚举。
使用组合:
public class AppleList : FruitList<Apple> { ... }
public class OrangeList : FruitList<Orange> { ... }
public class LemonList : FruitList<Lemon> { ... }
将通用逻辑放在基类列表中:
public class FruitList<T> : List<T>
where T : IFruit
{ ... }
如果您使用泛型,是否有创建FruitList类型的目的? 你能用List吗?
性能没有太大差异,所以我说为什么要创建三个不同的类,当一个人做同样的事情时? 使用通用解决方案。
维护1个通用列表要比3个非泛型版本容易得多。 如果你真的喜欢AppleList名称,你总是可以使用using技巧来命名一个通用列表
using AppleList=Fruit.FruitList<Fruit.Apple>
只有在添加其他功能时,才重用通用集合类并将其子类化。 如果可以的话,保持子类实现的通用性。 这是最不复杂的实现。
•所有ID都是int类型。
•水果的类型不会影响List本身的实现。 它只会被列表的客户端使用,就像外部方法一样。
鉴于这两个事实,我不会打扰泛型。 我会在FruitList上放一个普通的属性来指示它是哪种类型的水果。
我不会推荐接受的答案,我认为你的意思是:
public enum Fruit
{
Apple,
Orange,
Lemon
}
public interface IFruitList : IList<int>
{
Fruit Type { get; }
};
public class FruitList : List<int>, IFruitList
{
private readonly type;
FruitList(Fruit type)
: base()
{
this.type = type;
}
FruitList(Fruit type, IEnumerable<int> collection)
: base(collection)
{
this.type = type;
}
Fruit Type { return type; }
}
使用Generic列表,在crating 3列表中没有任何意义,保持抽象级别始终是好的。 (IFruit将是一个很好的界面)。
除非你需要,你应该假设YAGNI 。 因此,如果您不需要比List中更多的antyhing,那么只需要List<T>
。 如果由于某种原因你必须覆盖List,那么创建
FruitList<T> : List<T> where T : Fruit
如果您的列表不同并且不再是多态的,那么请考虑实现您的自定义列表:
AppleList
OrangeList
LemonList
但是,尽可能地尽可能保持继承层次结构尽可能平坦,以避免使解决方案过于复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.