gpt4 book ai didi

c# - 如何为多个foreach实现正确的IEnumerator接口(interface)?

转载 作者:太空狗 更新时间:2023-10-30 00:05:50 25 4
gpt4 key购买 nike

我有这样的代码:

        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我在 List 和 Collection 上测试了它,他们做对了。我怎样才能达到我的需要?

最佳答案

你不能,因为你已经让你的代码表面成为一个单一的枚举器,这本身就是一个错误的 IMO。对我来说,更好的版本是:

class T : IEnumerable<int> {
public IEnumerator<int> GetEnumerator() {
int i = 0;
while(i < 5) {
yield return i;
i++;
}
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

编译器将创建正确的设备以使用单独的枚举器实现此目的。

除非您正在为 .NET 1.1 编写代码,否则如果您发现自己手动编写一个枚举器,则很有可能您正在以艰难的方式完成它,并且错误地作为奖励.

如果您真的必须以艰难的方式做到这一点:

class T : IEnumerable<int>
{
public T() { }

public IEnumerator<int> GetEnumerator() { return new TEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
private class TEnumerator : IEnumerator<int>
{
private int position = -1;
public int Current { get { return position; } }
object IEnumerator.Current { get { return Current; } }
void IDisposable.Dispose() {}
public bool MoveNext()
{
position++;
return (position < 5);
}
public void Reset() { position = -1; }
}
}

这里的意义在于,TEnumerator 的不同实例允许相同 T 实例被单独迭代。

关于c# - 如何为多个foreach实现正确的IEnumerator接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7658449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com