Como faço para implementar IEnumerable <T>
Eu sei como implementar o IEnumerable não genérico, como este:
using System;
using System.Collections;
namespace ConsoleApplication33
{
class Program
{
static void Main(string[] args)
{
MyObjects myObjects = new MyObjects();
myObjects[0] = new MyObject() { Foo = "Hello", Bar = 1 };
myObjects[1] = new MyObject() { Foo = "World", Bar = 2 };
foreach (MyObject x in myObjects)
{
Console.WriteLine(x.Foo);
Console.WriteLine(x.Bar);
}
Console.ReadLine();
}
}
class MyObject
{
public string Foo { get; set; }
public int Bar { get; set; }
}
class MyObjects : IEnumerable
{
ArrayList mylist = new ArrayList();
public MyObject this[int index]
{
get { return (MyObject)mylist[index]; }
set { mylist.Insert(index, value); }
}
IEnumerator IEnumerable.GetEnumerator()
{
return mylist.GetEnumerator();
}
}
}
No entanto, também noto que IEnumerable tem uma versão genérica,IEnumerable<T>
, mas não consigo descobrir como implementá-lo.
Se eu adicionarusing System.Collections.Generic;
para minhas diretivas usando e, em seguida, altere:
class MyObjects : IEnumerable
para:
class MyObjects : IEnumerable<MyObject>
E então clique com o botão direitoIEnumerable<MyObject>
e selecioneImplement Interface => Implement Interface
, O Visual Studio adiciona o seguinte bloco de código:
IEnumerator<MyObject> IEnumerable<MyObject>.GetEnumerator()
{
throw new NotImplementedException();
}
Retornando o objeto IEnumerable não genérico doGetEnumerator();
método não funciona desta vez, então o que eu coloco aqui? A CLI agora ignora a implementação não genérica e segue direto para a versão genérica quando tenta enumerar minha matriz durante o loop foreach.