2009-10-21 68 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()這兩種形式。