如何为多个foreach实现正确的IEnumerator接口?
我有这样的代码:
class T : IEnumerable, IEnumerator
{
private int position = -1;
public T() { }
public IEnumerator GetEnumerator() { return this; }
public object Current { get { return position; } }
public bool MoveNext()
{
position++;
return (position < 5);
}
public void Reset() { position = -1; }
}
//Using in code:
T t = new T();
foreach (int i in t)
//to do something
在上面的代码中,所有内容都工作正常,但是当我使用 next 时:
foreach (int i in t)
if (i == 2)
foreach (int p in t)
//print p
else
//print i
它打印(在括号中的第二个循环中): 0 1 (3 4) 2 而不是 0 1 (0 1 2 3 4) 2 3 4 我在列表和集合上测试了它,他们做得正确。 我怎样才能达到我所需要的?
I have a code like:
class T : IEnumerable, IEnumerator
{
private int position = -1;
public T() { }
public IEnumerator GetEnumerator() { return this; }
public object Current { get { return position; } }
public bool MoveNext()
{
position++;
return (position < 5);
}
public void Reset() { position = -1; }
}
//Using in code:
T t = new T();
foreach (int i in t)
//to do something
In the code above all is working fine but when I use next:
foreach (int i in t)
if (i == 2)
foreach (int p in t)
//print p
else
//print i
It prints (in brackets second loop): 0 1 (3 4) 2 instead of 0 1 (0 1 2 3 4) 2 3 4
I tested It on List and Collection and they do It right.
How can I to achive what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能,因为你已经让你的代码表面成为一个枚举器,在我看来,这本身就是一个错误。对我来说,更好的版本是:
编译器将创建正确的设备来使用单独的枚举器来实现此目的。
除非您正在为 .NET 1.1 编写代码,否则如果您发现自己手动编写了一个枚举器,那么很有可能您的做法很困难,而且还可能会出错。
如果您确实必须采取困难的方式:
这里的意义在于
TEnumerator
的不同实例允许相同要单独迭代的T
实例。You can't because you have made your code surface a single enumerator, itself a mistake IMO. A better version would be, for me:
The compiler will create the right devices to achieve this with separate enumerators.
Unless you are writing for .NET 1.1, then if you find yourself manually writing an enumarator, there's a very good chance that you are doing it the hard way, and getting it wrong as a bonus.
If you really must do it the hard way:
The significance here is that different instances of
TEnumerator
allow the sameT
instance to be iterated separately.首先总是使用大括号,当你缩进匹配另一个
if
时会发生什么,这会让事情变得混乱。但您会遇到问题:每个
T
实例只有一个计数器,并且您使用的是同一个实例。因此你做一次。如果您希望允许并发枚举,则枚举器对象需要与每次返回一个新实例的GetEnumerator
分开。First always use braces, while you indenting matches what will happen another
if
in there will confuse things.But you problem: you only have one counter per instance of
T
, and you are using the same instance. Therefore you do through once. If you want to allow concurrent enumerations the enumerator object will need to be separate withGetEnumerator
returning a new instance each time.