2012-07-03 19 views
10

Chciałbym, aby mój typ implementował IEnumerable<string>. Starałem się śledzić C# w pigułce, ale coś poszło nie tak:Jak zaimplementować IEnumerable <T> za pomocą narzędzia GetEnumerator()?

public class Simulation : IEnumerable<string> 
{ 
    private IEnumerable<string> Events() 
    { 
     yield return "a"; 
     yield return "b"; 
    } 

    public IEnumerator<string> GetEnumerator() 
    { 
     return Events().GetEnumerator(); 
    } 
} 

Ale pojawia się błąd kompilacji

Error 1 'EventSimulator.Simulation' nie wykona „System.Collections członków interfejs. IEnumerable.GetEnumerator() ". "EventSimulator.Simulation.GetEnumerator()" nie może zaimplementować "System.Collections.IEnumerable.GetEnumerator()", ponieważ nie ma zgodnego typu powrotu "System.Collections.IEnumerator".

+0

Na marginesie: możesz "zwrócić return' bezpośrednio od wewnątrz' GetEnumerator() ' – AlexFoxGill

Odpowiedz

25

Brakuje IEnumerator IEnumerable.GetEnumerator():

public class Simulation : IEnumerable<string> 
{ 
    private IEnumerable<string> Events() 
    { 
     yield return "a"; 
     yield return "b"; 
    } 

    public IEnumerator<string> GetEnumerator() 
    { 
     return Events().GetEnumerator(); 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 
+2

Dzięki temu zadziałało. –

+0

Miał pytanie, ale @NominSim odpowiedział na to w postu poniżej - nieważne! –

+0

dziękuję, teraz mogę dodać to do mojego pliku EF TT ;-) –

4

IEnumerable wymaga wdrożenia zarówno wpisane i sposób ogólny.

W sekcji społeczności msdn docs wyjaśnia, dlaczego potrzebujesz obu. (Dla kompatybilności wstecz jest to podstawa podana w zasadzie).

Powiązane problemy