GetEnumerator, yield关键字
2011-03-14 09:25 Dirichlet 阅读(216) 评论(0) 编辑 收藏 举报1. 使用了yield关键字,就不需要人工再实现下面的IEnumerator接口了
namespace System.Collections { public interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } }
2. code sample
using System; using System.Collections.Generic; namespace serialization { class Program1 { public static void Main1(string[] args) { TestManager testManager = new TestManager(); foreach (string item in testManager) { Console.WriteLine(item); } } } class TestManager { private List<string> internalObjests = new List<string>(); public TestManager() { string[] stringArray = new string[] { "item 1", "item 2", "item 3", "item 4", "item 5" }; //Array this.internalObjests.AddRange(stringArray); } public System.Collections.IEnumerator GetEnumerator() { foreach (string item in this.internalObjests) { yield return item; } } } }
dfdf