泛型类的创建和使用

有些人问我"面向对象编程(OOP)的承诺在哪里?",我的回答是应该从两个方面来看OOP:你所使用的OOP和你创建的OOP。如果我们简单地看一下如 果没有如例如Microsoft的.NET,Borland的VCL,以及所有的第三方组件这样的OO框架,那么很多高级的应用程序几乎就无法创建。所 以,我们可以说OOP已经实现了它的承诺。不错,生产好的OOP代码是困难的并且可能是极具挫败性的;但是记住,你不必须一定要通过OOP来实现你的目 标。因此,下面首先让我们看一下泛型的使用。

当你用Visual Studio或C# Express等快速开发工具创建工程时,你会看到对于System.Collections.Generic命名空间的参考引用。在这个命名空间中,存 在若干泛型数据结构-它们都支持类型化的集合,散列,队列,栈,字典以及链表等。为了使用这些强有力的数据结构,你所要做的仅是提供数据类型。

列表1显示出我们定义一个强类型集合的Customer对象是很容易的。

列表1 这个控制台应用程序包含一个Customer类和一个基于List<T>的强类型集合Customers。

using System;
using System.Collections.Generic;
using System.Text;
namespace Generics{
class Program{
static void Main(string[] args){
List<Customer> customers = new List<Customer>();
customers.Add(new Customer("Motown-Jobs"));
customers.Add(new Customer("Fatman's"));
foreach (Customer c in customers)
Console.WriteLine(c.CustomerName);
Console.ReadLine();
}
}
public class Customer{
private string customerName = "";
public string CustomerName{
get { return customerName; }
set { customerName = value; }
}
public Customer(string customerName){
this.customerName = customerName;
}
}
}

注意,我们有一个强类型集合-List<Customer>-对这个集合类本身来说不需要写一句代码。如果我们想要扩展列表customer,我们可以通过从List<Customer>继承而派生一个新类。
posted @ 2009-11-07 23:02  金色眼球  阅读(494)  评论(0编辑  收藏  举报