现在的位置: 首页 > 综合 > 正文

(2)学习集合,引申学习索引器和泛型

2012年04月13日 ⁄ 综合 ⁄ 共 1948字 ⁄ 字号 评论关闭
有1个Person类,下面我们要在前台利用集合去定义3个Person对象,然后返回这3个对象的Name

public class Person
{
    private string _firstName;
    private string _lastName;

    public string Name
    {
        get
        {
            return _firstName + _lastName;
        }
    }

    public Person(string strFirstName, string strLastName)
    {
        _firstName = strFirstName;
        _lastName = strLastName;
    }
}

(1)使用数组
protected void Page_Load(object sender, EventArgs e)
{
    Person[] myPerson = new Person[3];
    myPerson[0] = new Person("Jim", "Jack");
    myPerson[1] = new Person("Jim", "Andy");
    myPerson[2] = new Person("Sun", "Bob");

    for (int i = 0; i < myPerson.Length; i++)
    {
        lblName.Text += myPerson[i].Name + "<br />";
    }
}

页面显示如下:
JimJack
JimAndy
SunBob

(2)使用ArrayList
protected void Page_Load(object sender, EventArgs e)
{
    ArrayList myArrayListPerson = new ArrayList();
    myArrayListPerson.Add(new Person("Jim", "Jack"));
    myArrayListPerson.Add(new Person("Jim", "Andy"));
    myArrayListPerson.Add(new Person("Sun", "Bob"));

    for (int i = 0; i < myArrayListPerson.Count; i++)
    {
        lblName.Text += ((Person)myArrayListPerson[i]).Name + "<br />";
    }
}

页面显示如下:
JimJack
JimAndy
SunBob

说明:
注意紫色代码部分,使用ArrayList获得Name时,我们需要进行强制转换,这样做是有风险的.(具体什么风险,等查阅相关书籍后补充)

(3)为了避免上面的风险,我们使用泛型
protected void Page_Load(object sender, EventArgs e)
{
    List<Person> myPerson = new List<Person>();
    myPerson.Add(new Person("Jim", "Jack"));
    myPerson.Add(new Person("Jim", "Andy"));
    myPerson.Add(new Person("Sun", "Bob"));

    for (int i = 0; i < myPerson.Count; i++)
    {
        lblName.Text += myPerson[i].Name + "<br />";
    }
}

页面显示如下:
JimJack
JimAndy
SunBob

说明:
1. 这里我们使用了System.Collections.Generic命名空间里已经定义好的一个泛型类List
2. 先简单说明下System.Collections.Generic命名空间里的类,具体见第二部分的详细说明
List 是对应于 ArrayList 的泛型类。
Dictionary 是对应于 Hashtable 的泛型类。
Collection 是对应于 CollectionBase 的泛型类。Collection 可以用作基类,但是与 CollectionBase 不同的是它不是抽象的,因而更易于使用。
ReadOnlyCollection 是对应于 ReadOnlyCollectionBase 的泛型类。ReadOnlyCollection 不是抽象的,它具有一个构造函数,该构造函数使其更易于将现有的 List 公开为只读集合。
Queue、Stack 和 SortedList 泛型类分别对应于与其同名的非泛型类。
具体可以参考http://msdn2.microsoft.com/zh-cn/library/ms172181(VS.80).aspx何时使用泛型集合

抱歉!评论已关闭.