C#学习笔记(泛型)

1 基本概念

  泛型类是以实例化过程中提供的类型或类为基础建立的,可以毫不费力的对对象进行强类型转化。对于集合,创建“T”类型对象的集合十分简单,只要编写一行代码即可。不使用下面的代码:

CollectionClass items = new CollectionClass();

items.Add(new ItemClass());

而是使用:

CollectionClass<ItemClass> items = new CollectionClass<ItemClass>();

items.Add(new ItemClass());

  尖括号语法就是把类型参数传递给泛型类型的方式。在上面的代码中,应把CollectionClass<ItemClass>看做ItemClass的CollectionClass。

2 如何实现泛型

  通常,在创建类的时候,他会编译成为一个类型,然后在代码中使用。总之,泛型允许灵活的创建一种或多种特定的对象,这些类型是在实例化时确定的,否则就使用泛型类型。.NET Framework提供的泛型,包括System.Clooections.Generic名称空间的类型。

2.1 List<T>

  List<T>泛型集合类型更加快捷、易于使用。他的另一个好处就是正常情况下需要实现的许多方法(例如,Add())已经自动实现了。

  创建T型对象的集合需要如下代码:

  List<T> myCollection = new List<T>;

  其中使用这个语法实例化的对象支持下面的方法和属性(其中,提供个List<T>泛型的类型是T)

成员 说明
int Count 该属性给出集合中项的个数
void Add(T item) 把一个项添加到集合中
void AddRange(IEnumerable<T>) 把多个项添加到集合中
IList<T> AsReadOnly() 把集合返回一个只读接口
int Capacity() 获取成设置集合可以包含的项数
void Clear() 删除集合中的所有项
bool Contains(T item) 确定item是否包含在集合中
void CopyTo(T[] array,int index) 把集合中项复制到数组array中,从数组的索引index开始
IEnumerator<T> GetEnumerator() 获取一个IEnumerator<T>实例。用于迭代集合。
int IndexOf(T item) 获取item的索引,如果集合中并未包含该项,就返回-1
void Insert(int index,T item) 把item插入到集合的指定索引位置上
bool Remove(T item) 从集合中删除第一个item,并返回ture;如果不包含在集合中,就返回false
void RemoveAt(int index) 从集合中删除索引index处的项

示例代码:
static void Main(string[] args)

{

  List<Animal> animalCollection = new List<Animal>();

  animalCollection.Add(new Cow("Jack"));

  animalCollection.Add(new Chicken("Vera"));

  foreach(Animal myAnimal in animalCollection)

  {

    myAnimal.Feed();

  }

  Console.ReadKey();

}

原文地址:https://www.cnblogs.com/DannyShi/p/4513037.html