继承名单< T>实现集合一个坏主意? [英] Inheriting List<T> to implement collections a bad idea?

查看:95
本文介绍了继承名单< T>实现集合一个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经读过关于如何建立3层应用程序的文章Imaar Spaanjars。 (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.

因此​​,我实现的集合,因为他所做的一切,通过继承了列表< T> 。所以,如果我有一个名为Employee类,实现一个集我也会有一类员工如下图所示。

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.

例如。如果我想从员工,一个子集,如

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);



那么,如何实现员工让我没有明确地使用名单,LT ;员工> 在我的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?

推荐答案

我也不会从列表与LT继承; T> - 它引入了问题,如这些,并没有真正的帮助(因为没有虚拟方法重写)。我想要么使用列表< T> (或者更抽象的的IList< T> ),或引入多态收藏< 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选项(如。凡())是有用的同行; T> (或的IEnumerable< T> 任何的的IList<工作>),而不仅仅是列表< 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.

这篇关于继承名单&LT; T&GT;实现集合一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆