Multiple Enumerators for a Single C# Class

2019-02-14 06:26发布

问题:

I have created a data structure consisting of intervals. The data structure should naturally have an enumerator that enumerates all intervals, but I would like to expose two different enumerators that enumerate the intervals in different order.

One of the enumerators enumerate the intervals really fast, but in somewhat arbitrary order. The other enumerates them in lexicographical order, but a bit slower (depends on the intervals though). Depending on what you try to achieve, one enumerator might be to prefer over the other.

Is there a way to allow the user to decide which enumerator should be used in a foreach loop for instance? If not, I could easily have a property used for switching between the enumerators, or the constructor could take an additional parameter. But I'm a bit afraid that it will cause more confusion than convenience.

Should I rather, for the other enumerator, make a separate method that returns an IEnumerator? Is there a best practice for this little odd problem?

回答1:

Exposing two properties which return different enumerators is probably the right way to go. Instead of your data structure implementing IEnumerable itself (I'm guessing with that one), create two different IEnumerator implementations, and have a propery exposed from the main class for each one. Then the using code is straightforward:

foreach( var item in data.FastEnumerator )
{
    ....

foreach( var item in data.LexicalEnumerator )
{
    ....