新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#foreach使用實(shí)例淺析
C# foreach使用實(shí)例向你全面展示了C# foreach的使用規(guī)范,以及在C# foreach中特別要注意的關(guān)鍵是實(shí)現(xiàn)IEnumerable 和IEnumerator 這兩個接口:那么學(xué)習(xí)C# foreach這一C#新加入的語句,我們還是要多多練習(xí)和體會。

專注于為中小企業(yè)提供成都網(wǎng)站制作、做網(wǎng)站服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)南安免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了超過千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
C# foreach使用1. MySplit 類
- ///
- /// MySplit 類
- ///
- public class MySplit : IEnumerable
- {
- private string[] elements;
- public MySplit(string source, char[] delimiters)
- {
- elements = source.Split(delimiters);
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return new MyEnumerator(this);
- }
- #region 在嵌套類中實(shí)現(xiàn) IEnumerator 接口
- ///
- /// 在嵌套類中實(shí)現(xiàn) IEnumerator 接口,以便以后方便創(chuàng)建多個枚舉
- ///
- public class MyEnumerator : IEnumerator
- {
- private int position = -1;
- private MySplit t;
- public MyEnumerator(MySplit t)
- {
- this.t = t;
- }
- public bool MoveNext()
- {
- if (position < t.elements.Length - 1)
- {
- position++;
- return true;
- }
- else
- {
- return false;
- }
- }
- public void Reset()
- {
- position = -1;
- }
- object IEnumerator.Current
- {
- get
- {
- try
- {
- return t.elements[position];
- }
- catch (IndexOutOfRangeException)
- {
- throw new InvalidOperationException();
- }
- }
- }
- }
- #endregion
- }
C# foreach使用2. 使用過程(注意規(guī)范)
- MySplit mySplit = new MySplit("大豆男生: I Love You!", new char[] { ' ', '-' });
- foreach (string item in mySplit)
- {
- Console.WriteLine(item);
- }
C# foreach使用3. 程序輸出結(jié)果
- 大豆男生:
- I
- Love
- You!
C# foreach使用的情況就向你介紹到這里,希望對你了解和學(xué)習(xí)以及C# foreach使用有所幫助。
名稱欄目:C#foreach使用實(shí)例淺析
網(wǎng)站地址:http://www.dlmjj.cn/article/cdsiepi.html


咨詢
建站咨詢
