C# – 如何在类上实现IEnumerator

如何在这个类上实现IEnumerator,以便我可以在foreach循环中使用它。

public class Items { private Dictionary _items = new Dictionary(); public Configuration this[string element] { get { if (_items.ContainsKey(element)) { return _items[element]; } else { return null; } } set { _items[element] = value; } } } 

在此示例中,Configuration是一个具有很少属性的简单类。

只是一个实现类型安全IEnumerable而不是IEnumerator的例子,你可以在foreach循环中使用它。

  public class Items : IEnumerable { private Dictionary _items = new Dictionary(); public void Add(string element, Configuration config) { _items[element] = config; } public Configuration this[string element] { get { if (_items.ContainsKey(element)) { return _items[element]; } else { return null; } } set { _items[element] = value; } } public IEnumerator GetEnumerator() { return _items.Values.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _items.Values.GetEnumerator(); } } 

问候。

您应该能够像这样实现IEnumerator

 public class Items : IEnumerator> { private Dictionary _items = new Dictionary(); public Configuration this[string element] { get { if (_items.ContainsKey(element)) { return _items[element]; } else { return null; } } set { _items[element] = value; } } int current; public object Current { get { return _items.ElementAt(current); } } public bool MoveNext() { if (_items.Count == 0 || _items.Count <= current) { return false; } return true; } public void Reset() { current = 0; } public IEnumerator GetEnumerator() { return _items.GetEnumerator(); } KeyValuePair IEnumerator>.Current { get { return _items.ElementAt(current); } } public void Dispose() { //Dispose here } } 

但正如已经指出的那样,你也可以实现IEnumerable

您不需要实现IEnumerable或任何接口。 为了能够在foreach使用您的类,您需要的只是使用以下签名向您的类添加实例方法:

 IEnumerator GetEnumerator()