原文:http://msdn2.microsoft.com/zh-cn/library/0x6a29h6(VS.80).aspx
泛型通常用在集合和在集合上运行的方法中。.NET Framework 2.0 版类库提供一个新的命名空间 System.Collections.Generic,其中包含几个新的基于泛型的集合类。建议面向 2.0 版的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类,如 ArrayList。有关更多信息,请参见 .NET Framework 类库中的泛型(C# 编程指南)。
当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类。(大多数情况下,建议使用 .NET Framework 类库提供的 List 类,而不要自行创建类。)在通常使用具体类型来指示列表中所存储项的类型时,可使用类型参数 T。其使用方法如下:
在 AddHead 方法中作为方法参数的类型。
在 Node 嵌套类中作为公共方法 GetNext 和 Data 属性的返回类型。
在嵌套类中作为私有成员数据的类型。
注意,T 可用于 Node 嵌套类。如果使用具体类型实例化 GenericList(例如,作为 GenericList),则所有的 T 都将被替换为 int。
// type parameter T in angle brackets
public class GenericList
{
// The nested class is also generic on T
private class Node
{
// T used in non-generic constructor
public Node(T t)
{
next = null;
data = t;
}
private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}
// T as private member data type
private T data;
// T as return type of property
public T Data
{
get { return data; }
set { data = value; }
}
}
private Node head;
// constructor
public GenericList()
{
head = null;
}
// T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
下面的代码示例演示客户端代码如何使用泛型 GenericList 类来创建整数列表。只需更改类型参数,即可方便地修改下面的代码示例,创建字符串或任何其他自定义类型的列表:
class TestGenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>();
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("nDone");
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/7764484/viewspace-903168/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/7764484/viewspace-903168/
1582

被折叠的 条评论
为什么被折叠?



