Multiple Enumerators for a Single C# Class

一笑奈何 提交于 2019-12-19 03:27:24

问题


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 )
{
    ....


来源:https://stackoverflow.com/questions/17759805/multiple-enumerators-for-a-single-c-sharp-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!