我有这个代码

public class SomeClass<T>: IEnumerable<T>
{
    public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

    public IEnumerator<T> GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

如何从MyList中提取IEnumerator?

感谢StackoverFlower ....

有帮助吗?

解决方案

此:

public List<SomeClass<T>> MyList = new List<SomeClass<T>>();

需要这样:

public List<T> MyList = new List<T>();

然后,这应该工作:

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

你不能拥有

List<SomeClass<T>>

您拉取枚举器,因为您已在接口中指定枚举器将返回&lt; T&gt; 的可枚举项。您还可以将 IEnumerable&lt; T&gt; 更改为

IEnumerable<SomeClass<T>>

并将枚举器更改为

public IEnumerator<SomeClass<T>> Getenumerator ()
{
  foreach (var item in MyList){
     yield return item;}
}

其他提示

琐碎的选项是返回MyList.GetEnumerator()

Kevins的答案是正确是懒惰的(甚至更好)。如果您使用Trodek响应,将抛出以下异常:

Cannot implicitly convert type `System.Collections.Generic.List<SomeClass<T>>.Enumerator' to `System.Collections.Generic.IEnumerator<T>'(CS0029)

尽管如此我想添加评论。当您使用 yield return 时,会生成一个状态机,它将返回不同的值。如果要使用yield返回将使用嵌套数据结构(例如树)将分配更多内存,因为将在每个子结构中创建不同的状态机。

嗯,那是我的两分钱!

假设有一种方法可以从对象SomeClass中获取对象T,

public IEnumerator<T> GetEnumerator()
{
    return MyList.Select(ml => ml.GetT() /* operation to get T */).GetEnumerator();
}

如果收到消息

,则作为已接受答案的补充
MyNamespace.MyClass<T>' does not implement interface
  member 'System.Collections.IEnumerable.GetEnumerator()'.
  'WindowsFormsApplication1.SomeClass<T>.GetEnumerator()' cannot implement
  'System.Collections.IEnumerable.GetEnumerator()' because it does not have
  the matching return type of 'System.Collections.IEnumerator'.

您需要实现其他 GetEnumerator()方法:

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

IEnumerable&lt; T&gt; 实现 IEnumerable ,因此必须实现 GetEnumerator()两种形式。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top