using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 泛型_一__什么是泛型
{
public class GenericList<T>
{
private class Node
{
//字段
private Node next;
private T data;
//有参构造函数
public Node(T t)
{
next = null;
data = t;
}
//属性 next
public Node Next
{
get
{
return next;
}
set
{
next = value;
}
}
public T Data
{
get
{
return data;
}
set
{
data = value;
}
}
}
//字段
private Node head;
//无参构造函数
public GenericList()
{
head = null;
}
//方法1
//给Node添加元素
public void AddHead(T t)
{
Node n = new GenericList<T>.Node(t);
n.Next = head;
head = n;
}
//方法2
//IEnumerator<T> 接口,支持在泛型集合上进行简单的迭代
//yield return 语句返回集合的一个元素,并移动到下一个元素上. yield break可停止迭代.
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current !=null )
{
yield return current.Data;
current = current.Next;
}
}
}
class Program
{
static void Main(string[] args)
{
//GenericList<T> 定义泛型类的对象list,并给予模板参数T为int型
GenericList<int> list = new GenericList<int>();
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
foreach (int i in list)
{
System.Console.WriteLine(" " + i);
}
Console.WriteLine("/nDone/n");
Console.ReadKey();
GenericList<string> stringList = new GenericList<string>();
for (int x = 0; x < 10; x++)
{
stringList.AddHead(x.ToString()+"****");
}
foreach (string str in stringList)
{
Console.WriteLine(" " + str);
}
Console.WriteLine("/nDone/n");
Console.ReadKey();
}
}
}