gpt4 book ai didi

c# - IEnumerable 的实现

转载 作者:行者123 更新时间:2023-11-30 16:33:28 25 4
gpt4 key购买 nike

我有一个代码:

    public sealed class Sequence : IEnumerable<MyClass>
{
List<MyClass> _elements;

public IEnumerator<MyClass> Getenumerator()
{
foreach (var item in _elements)
{
yield return item;
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return this._elements.GetEnumerator();
}
}


// ....

Sequence s = new Sequence();

// ...
// filling s with some data
// ...

foreach(MyClass c in s)
{
// some action
}

该代码不想编译。它不想编译。 使用泛型类型“System.Collections.Generic.IEnumerator”需要“1”个类型参数

帮我重写 MyClass 以支持枚举。

我尝试了几种组合,使用了 Google。没有泛型的 Enumerable 和 IEnumerator 的例子无处不在。

最佳答案

添加行:

using System.Collections;

您想使用 System.Collections.IEnumerator , 不是 System.Collections.Generic.IEnumerator<T> .

关于c# - IEnumerable<T> 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3178262/

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