C#泛型:列表<对象>或新类扩展列表<对象> [英] C# Generics : List<Object> or new class extends List <Object>
问题描述
我有一个类叫做产品在我的业务对象,并在另一个类,我想退掉这class.Which方法,我应该使用对象的列表?
I have a class called Product in my Business object and in another class i want to return a list of objects of this class.Which approach i should use ?
public static List<Product> GetProductList() { .... }
或建立在我的业务对象namspace另一类称为产品列表哪些扩展列表<产品>
如下:
or create another class in my Business object namspace called ProductList which extends List <Products>
as follows:
public class ProductList :List<Products > { .... }
和使用它有
public static ProductList GetProductList() { .... }
有没有这两者之间有什么区别?如何ABT内存分配和性能?
Is there any difference between these two ? How abt the memory allocation and performance ?
推荐答案
有是有一个额外的类型(小的开销产品列表
),但没有巨大的。但它的真正的取决于你想要做什么。在许多方面,产品
仍然是一个糟糕的主意,因为它燃烧列表< T>
进入公共API和列表< T>
不是很可扩展(没有一种方法是虚拟
,例如)。 收藏< T>
可能有更多的可扩展性选项
There is a small overhead in having an extra type (ProductList
), but nothing huge. But it really depends on what you want to do. In many ways, ProductList
is still a bad idea since it burns List<T>
into the public API, and List<T>
isn't very extensible (none of the methods are virtual
, for example). Collection<T>
might have more extensibility options.
我要说赞成抽象或封装:<。 / p>
I'd argue in favor of abstraction or encapsulation:
public static IList<Product> GetProductList() {...} // abstraction; can return
// List<Product> if we want
或
public class ProductList : IList<Product> {...} // encapsulation, but need to
// add a lot of dull code
的
这是一个耻辱,C#不使封装方法简单(我想混入)。
It is a shame that C# doesn't make the encapsulation approach simple (I'm thinking "mixins").
请注意,另一个伎俩(有时是合适的,有时不)是使用扩展方法来添加额外的方法错觉的IList<产品>
...这是一个棘手的辩论,所以我只是提到它,不是说做到这一点。
Note that another trick (sometimes suitable, sometimes not) would be to use extension methods to add the illusion of extra methods on IList<Product>
... this is a tricky debate, so I'm just mentioning it, not saying "do this".
这篇关于C#泛型:列表<对象>或新类扩展列表<对象>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!