C# - 如何实现一个类的IEnumerator
问题描述:
如何实现这个类的IEnumerator,这样我可以在foreach循环使用它。
How to implement IEnumerator on this class so that I can use it in foreach loop.
public class Items
{
private Dictionary<string, Configuration> _items = new Dictionary<string, Configuration>();
public Configuration this[string element]
{
get
{
if (_items.ContainsKey(element))
{
return _items[element];
}
else
{
return null;
}
}
set
{
_items[element] = value;
}
}
}
在这个例子中配置是一简单的类具有一些属性。
In this example Configuration is a simple class with few properties.
答
只是一个例子来实现类型安全的的IEnumerable
而不是的IEnumerator
,你将可以在foreach循环使用。
Just an example to implement typesafe IEnumerable
and not IEnumerator
which you will be able to use in foreach loop.
public class Items : IEnumerable<Configuration>
{
private Dictionary<string, Configuration> _items = new Dictionary<string, Configuration>();
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<Configuration> GetEnumerator()
{
return _items.Values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _items.Values.GetEnumerator();
}
}
问候。
Regards.