數組,集合,IEnumerable介面,迭代器

來源:互聯網
上載者:User

發展:數組-->集合-->泛型

(1)數組
1. 數組資料結構是System.Array類的一個執行個體.
2. System.Array類的文法為
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Array : ICloneable, IList, ICollection, IEnumerable
3. 下面看一個使用數組的例子(我稱之為隱式實現)
protected void Page_Load(object sender, EventArgs e)
{
    string[] strArrName = new string[3] { "Jim", "Andy", "Sun" };
    foreach (string strName in strArrName)
    {
        lblName.Text += strName + ",";
    }
}
或者這樣寫
protected void Page_Load(object sender, EventArgs e)
{
    string[] strArrName = new string[3];
    strArrName[0] = "Jim";
    strArrName[1] = "Andy";
    strArrName[2] = "Sun";
    foreach (string strName in strArrName)
    {
        lblName.Text += strName + ",";
    }
}
顯示結果如下
Jim,Andy,Sun,
4. 下面看另一個使用數組的例子(我稱之為顯式實現)
protected void Page_Load(object sender, EventArgs e)
{
    Array myArray = Array.CreateInstance(typeof(string), 3);
    myArray.SetValue("Jim", 0);
    myArray.SetValue("Andy", 1);
    myArray.SetValue("Sun", 2);
    foreach (string strName in myArray)
    {
        lblName.Text += strName + ",";
    }
}
顯示結果如下
Jim,Andy,Sun,
5. 優點:可以高效的訪問給定下標的元素;System.Array類有自己的C#文法,使用它編程非常的直觀.
6. 缺點:在執行個體化時必須指定數組的大小,以後也不能添加,插入,刪除元素.

(2)集合
1. 針對數組資料結構的缺點,我們使用集合資料結構.
2. 集合資料結構中的類都位於System.Collections命名空間中.
3. 說到集合,我們必須先瞭解幾個介面.想具體瞭解以下介面,可參考(3)集合介面
3.1 IEnumerable介面和IEnumerator介面
3.2 ICollection介面
public interface ICollection : IEnumerable
3.3 IList介面
public interface IList : ICollection, IEnumerable
3.4 IDictionary介面
public interface IDictionary : ICollection, IEnumerable
4. 說明一下:
4.1 ICollection介面是System.Collections命名空間中類的基底介面.
4.2 ICollection介面擴充IEnumerable;IDictionary和IList則是擴充ICollection的更為專用的介面.IDictionary實現是鍵/值對的集合,如Hashtable類.IList實現是值的集合,其成員可通過索引訪問,如ArrayList類.
4.3 某些集合(如Queue類和Stack類)限制對其元素的訪問,它們直接實現ICollection介面.
4.4 如果IDictionary介面和IList介面都不能滿足所需集合的要求,則從ICollection介面派生新集合類以提高靈活性.

(3)IEnumerable介面和IEnumerator介面
1. 我的理解:只有實現了IEnumerable介面的資料結構類才能使用foreach語句,下面給出例子
//Person類
public class Person
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
    }
    public string LastName
    {
        get { return _lastName; }
    }

    public Person(string strFirstName, string strLastName)
    {
        this._firstName = strFirstName;
        this._lastName = strLastName;
    }
}
//PersonList集合,實現IEnumerable介面
public class PersonList : IEnumerable
{
    private Person[] _arrPerson;

    public PersonList(Person[] myArrPerson)
    {
        _arrPerson = new Person[myArrPerson.Length];
        for (int i = 0; i < myArrPerson.Length; i++)
        {
            _arrPerson[i] = myArrPerson[i];
        }
    }

    public IEnumerator GetEnumerator()
    {
        return new PeopleEnumerator(_arrPerson);
    }
}
//實現IEnumerator介面
public class PeopleEnumerator : IEnumerator
{
    private int _position = -1;
    public Person[] _arrPerson;

    public object Current
    {
        get
        {
            try
            {
                return _arrPerson[_position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }

    public PeopleEnumerator(Person[] myArrPerson)
    {
        _arrPerson = myArrPerson;
    }

    public bool MoveNext()
    {
        _position++;
        return (_position < _arrPerson.Length);
    }

    public void Reset()
    {
        _position = -1;
    }
}
//集合的使用
protected void Page_Load(object sender, EventArgs e)
{
    Person[] myArrPerson = new Person[3]
    {
        new Person("John", "Smith"),
        new Person("Jim", "Johnson"),
        new Person("Sue", "Rabon"),
    };

    PersonList myPersonList = new PersonList(myArrPerson);
    foreach (Person myPerson in myPersonList)
    {
        lblName.Text += myPerson.FirstName + " " + myPerson.LastName + ",";
    }
}
6. 說明一下我的理解,定義了一個集合類,實現IEnumerable介面,則必須定義一個與之相應的實現IEnumerator介面的類,這樣是不是很麻煩呢?

(4)迭代器
1. 使用迭代器可避免上述麻煩,修改代碼,注意橙色部分
public class Person
{
    private string _firstName;
    private string _lastName;

    public string FirstName
    {
        get { return _firstName; }
    }
    public string LastName
    {
        get { return _lastName; }
    }

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

public class PersonList : IEnumerable
{
    private Person[] _arrPerson;

    public PersonList(Person[] myArrPerson)
    {
        _arrPerson = new Person[myArrPerson.Length];
        for (int i = 0; i < myArrPerson.Length; i++)
        {
            _arrPerson[i] = myArrPerson[i];
        }
    }

    public IEnumerator GetEnumerator()
    {
        //當編譯器檢測到迭代器時,它將自動產生IEnumerable或IEnumerable<T>介面的Current,MoveNext和Dispose方法. 
        for (int i = 0; i < _arrPerson.Length; i++)
        {
            yield return _arrPerson[i];
        }
    }
}

例子
實現IEnumerable介面的類可以進行簡單迭代,例如foreach語句

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace IEnumerable介面
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            foreach (int? var in a)//當int值可能被賦空值時用?

            {
                Console.WriteLine(var);
                
            }

        }
    }
    class A : IEnumerable
    {
        int x = 1;
        int y = 2;
        int z = 3;
        public IEnumerator GetEnumerator()
        {
           // int i = -1;
            for (int i = 0; i <=3; i++)
            {


                if (i == x)
                {
                    yield return 1;
                }
                else if (i == y)
                {
                    yield return 2;

                }
                else if (i == z)
                {
                    yield return 3;

                }
                else
                {
                    yield return null;
                }
            }
        }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.