集合与列表(3)
一、回顾
如何遍历Hashtable?
Hashtable hash = new Hashtable();
foreach (DictionaryEntry p in hash)
{
Person pp = p.Value as Person;
Response.Write(pp.FirstName + pp.LastName + "<br/>");
}
Response.Write("----------------<br/>");
foreach (Person p in hash.Values) //Values为Person的集合
{
Response.Write(p.FirstName + p.LastName + "<br/>");
}
二、集合和列表
1. 泛型的定义:泛型,就是创建使用通用类型的类或方法。
泛型旨在改进如下方面:
二进制代码的重用。
性能(不需要装箱和拆箱)。
易于阅读。
类型安全。
a)定义一个泛型方法
public void Swap<T>(ref T a, ref T b)
{
T temp;
temp = a;
a = b;
b = temp;
}
b)定义一个泛型类
public class Point<T>
{
private T xPos;
private T yPos;
public Point(T x, T y) {
xPos = x;
yPos = y;
}
public T X{
get { return xPos; }
set { this.xPos = value; }
}
public T Y{
get { return yPos; }
set { this.yPos = value; }
}
public override string ToString()
{
return string.Format("x:{0};y:{1}"
, xPos, yPos);
}
}
c)泛型列表
List<Person> list = new List<Person>();
list.Add(new Person("张", "三"));
list.Add(new Person("李", "四"));
list.Add(new Person("王", "五"));
Response.Write(list[0].FirstName + list[0].LastName);
Response.Write("<br/>-------------<br/>");
for (int i = 0; i < list.Count; i++)
{
Response.Write(list[i].FirstName + list[i].LastName + "<br/>");
}
d)泛型字典
Dictionary<string, Person> dic = new Dictionary<string, Person>();
dic.Add("zhang", new Person("张", "三"));
dic.Add("li", new Person("李", "四"));
dic.Add("wang", new Person("王", "五"));
Response.Write(dic["wang"].FirstName + dic["wang"].LastName + "<br/>");
foreach (string str in dic.Keys)
{
Response.Write(str + "<br/>");
}
foreach (Person p in dic.Values)
{
Response.Write(p.FirstName + p.LastName + "<br/>");
}
e)泛型集合Queue<T>
Queue<int> qu = new Queue<int>();
for (int i = 0; i < 10; i++)
{
qu.Enqueue(i);
}
for (int i = 0; i < 10; i++)
{
Response.Write(qu.Dequeue().ToString());
}
Response.Write("<br/>==================<br/>");
f)泛型集合Stack<T>
Stack<int> st = new Stack<int>();
for (int i = 0; i < 10; i++)
{
st.Push(i);
}
for (int i = 0; i < 10; i++)
{
Response.Write(st.Pop().ToString());
}