浏览:4372008-03-18 15:51   来自Ninety-Nine      :

利用泛型遍历任何类型的ArrayList??

哪位能帮忙写个方法。

楼主
  3个月前   PCJIM      :
// 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 list = new GenericList();

for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}

foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("\nDone");
}
}




回复  1楼 回到顶楼 
  3个月前   Ninety-Nine      :
@PCJIM
谢谢啊。
回复  2楼 回到顶楼 

你还不是小组成员,加入小组以后才能发布新主题!
1 24851