foreach原理學習

來源:互聯網
上載者:User

foreach能遍曆哪些什麼樣的資料類型?

   實現了IEnumerable(getEnumerator())、IEnumerable<T>的介面都可以使用foreach進行遍曆。那麼為什麼實現這兩個介面就有了遍曆的能力呢?查看這兩個介面的中繼資料IEnumerable介面中,就一個 GetEnumerator()方法 

    // 摘要:    //     公開枚舉數,該枚舉數支援在非泛型集合上進行簡單迭代。    [ComVisible(true)]    [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]    public interface IEnumerable    {        // 摘要:        //     返回一個逐一查看集合的枚舉數。        //        // 返回結果:        //     可用於逐一查看集合的 System.Collections.IEnumerator 對象。        [DispId(-4)]        IEnumerator GetEnumerator();    }

GetEnumerator()方法返回一個 可用於逐一查看集合的 System.Collections.IEnumerator 對象。

再通過查看IEnumerator介面的中繼資料

  // 摘要:    //     支援對非泛型集合的簡單迭代。    [ComVisible(true)]    [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]    public interface IEnumerator    {        object Current { get; }
        bool MoveNext();        void Reset();    }

在IEnumerator介面中,定義了Current 屬性和MoveNext()以及Reset()方法

可以看到Current 屬性只有get屬性,而沒有set屬性

Current屬性是擷取當前元素值,MoveNext()方法傳回值是bool類型,其作用是尋找下一個元素,如果找到,元素則為Current屬性,且返回true,否則返回fase.

Reset()讓當前返回到第一個元素。

大致瞭解完原理之後,就可以自己寫一個能被foreach遍曆的類

自訂類

    public class MyList<T> : IEnumerable, IEnumerator
{
T[] array;
int index = -1;
private MyList()
{
}
public MyList(int count)
{
array=new T[count];
}
public void Add(T item)
{
index++;
array[index] = item;
}
#region IEnumerator 成員
public object Current
{
get { return array[index]; }
}

public bool MoveNext()
{
bool result=false;
if (index < array.Length - 1)
{
index++;
result = true;
}
return result;
}

public void Reset()
{
index = -1;
}
#endregion

#region IEnumerable 成員
public IEnumerator GetEnumerator()
{
return this;
}
#endregion
}

編寫測試方法

View Code

      MyList<int> array = new MyList<int>(3);
array.Add(1);
array.Add(2);
array.Add(3);
array.Reset();
foreach (var item in array)
{
Console.WriteLine(item);
}
Console.WriteLine("Done");
Console.Read();

程式運行結果

 foreach時,為什麼不能對迭代出來的元素賦值,因為IEnumerator介面中定義的Current 屬性只有get屬性,而沒有set屬性

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.