2009-10-21 2 views
3

나는 내가 myList에에서있는 IEnumerator를 추출 할 수있는 방법이 코드있는 IEnumerator <T> 구현

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

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

있나요?

감사 StackoverFlower ....

+5

왜'MyList'는'T' 대신'SomeClass '의 모음입니까? – jasonh

+0

사실 트리 컬렉션을 구현 중이므로 실제로 myList는 자식 컬렉션입니다. 나는 그것을 언급 했어야했다 ... –

답변

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>> 
,536을 가질 수 없습니다 열거 자에서 <T>의 열거 가능 항목을 반환한다는 것을 인터페이스에 지정했기 때문에 열거자를 for에 대한

을 가져옵니다. 또한

IEnumerable<SomeClass<T>> 

을 할 IEnumerable<T>을 변경하고 (더 나은)

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

항목이 여전히 SomeClass 유형일까요? – CoderDennis

+0

'WindowsFormsApplication1.SomeClass '은 'System.Collections.IEnumerable.GetEnumerator()'인터페이스 요소를 구현하지 않습니다. 'WindowsFormsApplication1.SomeClass .GetEnumerator()'는 'System.Collections.IEnumerator'와 일치하는 반환 형식이 없으므로 'System.Collections.IEnumerable.GetEnumerator()'를 구현할 수 없습니다. – jasonh

+0

'yield'는 널리 간과 된 구성입니다. 언급하는 소품 :-) – CodeMonkey

1

사소한 옵션은 return MyList.GetEnumerator() 될 것이다.

+0

당신은 그것에 대해 확신합니까> 나는 코드를 지치지 않았지만 IEnumerator 대신 IEnumerator >을 반환 할 것입니다. mandel

+0

그냥 다음과 같은 오류가 발생합니다 :'System. '타입을 암묵적으로 변환 할 수 없습니다. Collection.Generic.List > .Enumerator 'to'System.Collections.Generic.IEnumerator '(CS0029) – mandel

+1

개체가 해당 클래스의 인스턴스 목록을 보유 할 예정입니까? 'public list '을 (를) 사용 하시겠습니까? – Tordek

1

Kevins의 대답은 올바른하고 게으름으로 열거을 변경할 수 있습니다. Trodek 응답을 사용하는 경우 다음 예외가 throw됩니다.

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

그럼에도 불구하고 댓글을 달고 싶습니다. 수익률 반환을 사용하면 다른 값을 반환하는 상태 시스템이 생성됩니다. yield 결과를 사용하여 중첩 된 데이터 구조 (예 : 나무)를 사용하려는 경우 모든 하위 구조마다 다른 상태 시스템이 작성되므로 훨씬 많은 메모리가 할당됩니다.

글쎄, 그건 내 두 센트 야! 당신이

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

당신이 필요로하는 메시지를받은 경우는 허용 대답에 추가 할 객체 SomeClass에서 객체 T를 얻을 수있는 방법이 가정

1

,

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

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

IEnumerable<T> 구현 : 추가 GetEnumerator() 방법을 구현하는 s IEnumerable이므로 두 형식 모두 GetEnumerator()을 구현해야합니다.