对于一个C#类中的多个枚举 [英] Multiple Enumerators for a Single C# Class

查看:266
本文介绍了对于一个C#类中的多个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已创建由间隔的数据结构。数据结构,自然应该有一个枚举所有间隔一个枚举,但我想揭露了枚举不同的顺序间隔两个不同的枚举器。

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.

有没有一种方法,让用户来决定哪些枚举应在使用foreach循环比如说?如果不是这样,我能轻松拥有用于枚举之间切换的属性或构造可能需要一个额外的参数。但我有点担心它会造成比便利更多的混乱。

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.

我应该相当,为其他枚举器,使返回一个IEnumerator一个单独的方法?是否有此有点古怪问题的最佳做法?

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?

推荐答案

揭露这两种性能返回不同的普查员可能是正确的方式去。相反,你的数据结构实施的IEnumerable 本身(我有一个猜测),创建两个不同的的IEnumerator 实现,并从每一个主类暴露属性格式。然后,使用代码是直截了当的:

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

这篇关于对于一个C#类中的多个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆