继承列表< T>实现集合一个坏主意? [英] Inheriting List<T> to implement collections a bad idea?
问题描述
我曾经读过Imaar Spaanjars的文章,介绍如何构建3层应用程序。 ( http:// imar .spaanjaars.com / 416 / building-layered-web-applications-with-microsoft-aspnet-20-part-1 ),这已经形成了我的编码的基础一段时间。
I once read an article by Imaar Spaanjars on how to build 3 tier applications. (http://imar.spaanjaars.com/416/building-layered-web-applications-with-microsoft-aspnet-20-part-1) which has formed the basis of my coding for a while now.
因此,通过继承一个 List< T>
,可以像他所做的那样实现集合。因此,如果我有一个类Employee,实现一个集合,我也将有一个类Employees如下。
Thus I implement collections as he has done, by inheriting a List<T>
. So if I have a class named Employee,to implement a collection I will also have a class Employees as below.
class Employee
{
int EmpID {get;set;}
string EmpName {get;set;}
}
class Employees : List<Employee>
{
public Employees(){}
}
从来没有真正质疑这是因为它为我做的工作。但现在我开始尝试一些事情,我不知道这是否是正确的方法。
I never really questioned this as it did the work for me. But now that I started trying out a few things I am not sure if this is the correct approach.
例如。如果我想从Employees获取子集,例如
e.g. if I want to get a subset from Employees, such as
Employees newEmployees = (Employees) AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);
这会抛出System.InvalidCastException异常。但是,如果我使用以下,则没有问题。
This throws a System.InvalidCastException . However, if I use the following then there is no Issue.
List<Employee> newEmployees = AllEmployees.FindAll(emp => emp.JoiningDate > DateTime.Now);
那么如何实现Employees,所以我不必显式使用 List< ; Employee>
在我的DAL或BLL中?或者我该如何摆脱InvalidCastexception?
So how do I implement Employees so that I dont have to explicitly use List<Employee>
in my DAL or BLL? Or maybe how do I get rid of the InvalidCastexception?
推荐答案
我不会继承 List< T>
- 它引入这样的问题,并没有真正帮助(因为没有 virtual
方法覆盖)。我将使用 List< T>
(或更抽象的 IList< T>
code>集合< T> 有个虚拟方法。
I wouldn't inherit from List<T>
- it introduces issues like these, and doesn't really help (since there are no virtual
methods to override). I would either use List<T>
(or the more abstract IList<T>
), or to introduce polymorphism Collection<T>
has virtual methods.
像 FindAll
,你也可以找到LINQ选项(如 .Where()
)有用的对手;最值得注意的是,它们将为任何 IList< T>
(或 IEnumerable< T>
),而不只是 List< T>
和子类。
As a note; re things like FindAll
, you may also find the LINQ options (like .Where()
) useful counterparts; most notably, they will work for any IList<T>
(or IEnumerable<T>
), not just List<T>
and subclasses.
这篇关于继承列表< T>实现集合一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!