How would you implement the IEnumerator interface?
I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom IEnumerator interface that iterates through the values.
public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection).
Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.
Raymond Chen's recent series of blog posts ("The implementation of iterators in C# and its consequences") is a good place to get up to speed.
Just implement the IEnumerable interface, no need to implement the IEnumerator unless you want to do some special things in the enumerator, which for your case doesn't seem to be needed.
public class Mapper<K,T> : IEnumerable<T> {
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
}
and that's it.
CreateEnumerable()
返回一个实现GetEnumerator()
的IEnumerable
public class EasyEnumerable : IEnumerable<int> {
IEnumerable<int> CreateEnumerable() {
yield return 123;
yield return 456;
for (int i = 0; i < 6; i++) {
yield return i;
}//for
}//method
public IEnumerator<int> GetEnumerator() {
return CreateEnumerable().GetEnumerator();
}//method
IEnumerator IEnumerable.GetEnumerator() {
return CreateEnumerable().GetEnumerator();
}//method
}//class
链接地址: http://www.djcxy.com/p/9114.html
上一篇: var关键字的确切用法是什么?
下一篇: 你将如何实现IEnumerator接口?