次のように、非ジェネリックIEnumerableを実装する方法を知っています。
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();
}
}
}
ただし、IEnumerableには汎用バージョンがあることにも気づきましたが、IEnumerable<T>それを実装する方法がわかりません。
using System.Collections.Generic;usingディレクティブに追加し、次に変更した場合:
class MyObjects : IEnumerable
に:
class MyObjects : IEnumerable<MyObject>
次に、右クリックしIEnumerable<MyObject>て[ ] を選択するとImplement Interface => Implement Interface、Visual Studioによって次のコードブロックが追加されます。
IEnumerator<MyObject> IEnumerable<MyObject>.GetEnumerator()
{
throw new NotImplementedException();
}
GetEnumerator();メソッドから非ジェネリックIEnumerableオブジェクトを返すことは今回は機能しないので、ここに何を入れますか?CLIは、非汎用の実装を無視し、foreachループ中に配列を列挙しようとすると、汎用バージョンに直接向かいます。
this.GetEnumerator()と単に返すことの間に違いはありGetEnumerator()ますか?