Vote count:
0
I have a class which encapsulates a collection of items we'll call ItemCollection. I need to expose two different enumerators for working with this collection: One simply enumerates all items (Item) and the second only enumerates those that are a specific derived type (T where T:Item). A wrinkle is that this part of some real time library code running on the compact framework and it really needs to avoid allocating objects on the heap that could trigger a collection in the middle of the foreach loop. I've been using struct Enumerators to fill that requirement.
public class ItemCollection
{
public ItemEnumerator GetEnumerator() {}
public ItemGenericEnumerator<T> GetEnumerator<T>() {} // Probably not correct
}
public struct ItemEnumerator : IEnumerator<Item>
{
Item Current;
bool MoveNext() {}
void Reset() {}
}
public struct ItemGenericEnumerator<T> : IEnumerator<T> where T : Item
{
T Current;
bool MoveNext() {}
void Reset() {}
}
On the face of it I don't see how to make a specific call to GetEnumerator<T> and indeed I started with this:
public class ItemCollection
{
public ItemEnumerator GetEnumerator() {}
public ItemGenericEnumerator<T> ItemsOfType<T>() {}
}
foreach(var item in collection.ItemsOfType<X>)
But I immediately ran into does not contain a public definition for 'GetEnumerator'.
One solution is to have ItemsOfType return a generic throw away class with a constructor that receives the enumerator and a single GetEnumerator method but that implementation breaks the no heap allocation requirement (would a throw away struct that returns another struct with GetEnumerator work?).
Another discarded option is to simply use the first enumerator and require the type to be checked manually, it's only one extra line of code. However the current implimentation details of ItemCollection mean there is a big difference between returning only items of one type compared to pulling all items and then sorting them outside the box.
Using a configurable enumerator
Aucun commentaire:
Enregistrer un commentaire