다음과 같이 비 제네릭 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()있습니까?