在向大家详细介绍C#实现泛型类之前,首先让大家了解下使用泛型集合,然后全面介绍C#实现泛型类。
使用泛型集合
有些人问我"面向对象编程(OOP)的承诺在哪里?",我的回答是应该从两个方面来看OOP:你所使用的OOP和你创建的OOP。如果我们简单地看一下如果没有如例如Microsoft的.NET,Borland的VCL,以及所有的第三方组件这样的OO框架,那么很多高级的应用程序几乎就无法创建。所以,我们可以说OOP已经实现了它的承诺。不错,生产好的OOP代码是困难的并且可能是***挫败性的;但是记住,你不必须一定要通过OOP来实现你的目标。因此,下面首先让我们看一下泛型的使用。
当你用Visual Studio或C# Express等快速开发工具创建工程时,你会看到对于System.Collections.Generic命名空间的参考引用。在这个命名空间中,存在若干泛型数据结构-它们都支持类型化的集合,散列,队列,栈,字典以及链表等。为了使用这些强有力的数据结构,你所要做的仅是提供数据类型。
显示出我们定义一个强类型集合的Customer对象是很容易的:
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;
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
注意,我们有一个强类型集合-List<Customer>-对这个集合类本身来说不需要写一句代码。如果我们想要扩展列表customer,我们可以通过从List<Customer>继承而派生一个新类。
C#实现泛型类
一种合理的实现某种新功能的方法是在原有的事物上进一步构建。我们已经了解强类型集合,并知道一种不错的用来构建泛型类的技术是使用一个特定类并删除数据类型。也就是说,让我们定义一个强类型集合CustomerList,并且来看一下它要把什么东西转化成一个泛型类。
定义了一个类CustomerList:
using System;
using System.Collections;
using System.Text;
namespace Generics{
public class CustomerList : CollectionBase{
public CustomerList() { }
public Customer this[int index]{
get { return (Customer)List[index]; }
set { List[index] = value; }
}
public int Add(Customer value)
{return List.Add(value);}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
【编辑推荐】