2009-10-21 69 views
3

我有这个代码IEnumerator的<T>实施

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

+5

为什么'MyList'是'SomeClass '而不是'T'的集合? – jasonh 2009-10-21 20:37:38

+0

因为我正在实现一个树集合,所以实际上myList是一个子集合。我应该提到它... – 2009-10-22 09:16:41

回答

8

此:

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>> 

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

IEnumerable<SomeClass<T>> 

,改变枚举是

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

是不是项目仍然是类SomeClass ? – CoderDennis 2009-10-21 20:28:01

+0

我得到:'WindowsFormsApplication1.SomeClass '没有实现接口成员'System.Collections.IEnumerable.GetEnumerator()'。 'WindowsFormsApplication1.SomeClass .GetEnumerator()'无法实现'System.Collections.IEnumerable.GetEnumerator()',因为它没有匹配的返回类型'System.Collections.IEnumerator'。 – jasonh 2009-10-21 20:36:37

+0

'yield'是一个被广泛忽视的构造..道具提及它:-) – CodeMonkey 2009-10-21 23:07:19

1

琐碎的办法是return MyList.GetEnumerator()

+0

你确定吗>我已经厌倦了代码,但从我的理解你将返回一个IEnumerator >而不是IEnumerator mandel 2009-10-21 20:14:41

+0

刚刚检查,你会得到以下错误:不能隐式转换类型'系统。 Collections.Generic.List > .Enumerator'到'System.Collections.Generic.IEnumerator '(CS0029) – mandel 2009-10-21 20:18:29

+1

对象是否意味着存放其类的实例列表?你是不是指'公开名单'? – Tordek 2009-10-21 21:15:43

1

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

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

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

那么,那些是我的两分钱!

1

假设有一种方式来获得一个对象T出一个对象SomeClass的的,

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

作为添加到接受的答案,如果您收到的邮件

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<T>实施s IEnumerable因此必须实施GetEnumerator()这两种形式。