如何在这个类上实现IEnumerator,以便我可以在foreach循环中使用它.
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,Configuration是一个具有很少属性的简单类.
Tig*_*ran 16
只是一个实现类型安全的示例,IEnumerable而不是IEnumerator您可以在foreach循环中使用的示例.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
问候.
你应该能够IEnumerator像这样实现:
public class Items : IEnumerator<KeyValuePair<string, Configuration>>
{
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;
}
}
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<string, Configuration> IEnumerator<KeyValuePair<string, Configuration>>.Current
{
get { return _items.ElementAt(current); }
}
public void Dispose()
{
//Dispose here
}
}
Run Code Online (Sandbox Code Playgroud)
但正如已经指出的那样,你也可以实施IEnumerable.
您不需要实现IEnumerable或任何接口。为了能够在 a 中使用您的类foreach,您只需要使用以下签名向您的类添加一个实例方法:
IEnumerator GetEnumerator()
Run Code Online (Sandbox Code Playgroud)