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>继承而派生一个新类。
三、 实现一个泛型类
一种合理的实现某种新功能的方法是在原有的事物上进一步构建。我们已经了解强类型集合,并知道一种不错的用来构建泛型类的技术是使用一个特定类并删除数据类型。也就是说,让我们定义一个强类型集合CustomerList,并且来看一下它要把什么东西转化成一个泛型类。
列表2定义了一个类CustomerList。后面的部分把CustomerList转化成List<T>。
列表2定义类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);}
}
}
四、 定义类头
如果我们定义一个泛型类,我们需要把类头转化成一个泛型类。所有我们需要做的是命名参数并且把类名改成某种泛型。List<T>只有一个参数T,并且因为我们在以一种向后兼容的方式工作,所以我们知道类名是List。列表3显示出列表2中类的新类头。
列表3 一个泛型类头显示出参数化
| 对此文章发表了评论 |

