Wiem, jak zaimplementować nieogólne IEnumerable, na przykład:
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();
}
}
}
Jednak zauważam również, że IEnumerable ma wersję ogólną, IEnumerable<T> , ale nie mogę dowiedzieć się, jak ją zaimplementować.
Jeśli dodam using System.Collections.Generic;do moich dyrektyw using, a następnie zmienię:
class MyObjects : IEnumerable
do:
class MyObjects : IEnumerable<MyObject>
Następnie kliknij prawym przyciskiem myszy IEnumerable<MyObject>i wybierz Implement Interface => Implement Interface, Visual Studio z pomocą dodaje następujący blok kodu:
IEnumerator<MyObject> IEnumerable<MyObject>.GetEnumerator()
{
throw new NotImplementedException();
}
Zwracanie nieogólnego obiektu IEnumerable z GetEnumerator();metody nie działa tym razem, więc co mam tutaj umieścić? Interfejs CLI ignoruje teraz nieogólną implementację i kieruje się bezpośrednio do wersji ogólnej, gdy próbuje wyliczyć moją tablicę podczas pętli foreach.
this.GetEnumerator()a zwykłym zwracaniemGetEnumerator()?