接口
using System;
using System.Collections;
// Declare the collection and implement the IEnumerable interface:
public class MyCollection: IEnumerable
{
int[] items;
public MyCollection()
{
items = new int[5] {12, 44, 33, 2, 50};
}
public MyEnumerator GetEnumerator()
{
return new MyEnumerator(this);
}
// Implement the GetEnumerator() method:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//以上两个接口实现方法可以用下面的一个方法代替
//
// public IEnumerator GetEnumerator()
// {
// return new MyEnumerator(this);
// }
// Declare the enumerator and implement the IEnumerator
// and IDisposable interfaces
public class MyEnumerator: IEnumerator, IDisposable
{
int nIndex;
MyCollection collection;
public MyEnumerator(MyCollection coll)
{
collection = coll;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return (nIndex < collection.items.GetLength(0));
}
public int Current
{
get
{
return (collection.items[nIndex]);
}
}
// The current property on the IEnumerator interface:
object IEnumerator.Current
{
get
{
return (Current);
}
}
public void Dispose()
{
Console.WriteLine("In Dispose");
collection = null;
}
}
}
public class MainClass
{
public static void Main(string [] args)
{
MyCollection col = new MyCollection();
Console.WriteLine("Values in the collection are:");
// Display collection items:
foreach (int i in col)
{
Console.WriteLine(i);
}
}
}
using System;
using System.Collections;
// Declare the collection and implement the IEnumerable interface:
public class MyCollection: IEnumerable
{
int[] items;
public MyCollection()
{
items = new int[5] {12, 44, 33, 2, 50};
}
public MyEnumerator GetEnumerator()
{
return new MyEnumerator(this);
}
// Implement the GetEnumerator() method:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//以上两个接口实现方法可以用下面的一个方法代替
//
// public IEnumerator GetEnumerator()
// {
// return new MyEnumerator(this);
// }
// Declare the enumerator and implement the IEnumerator
// and IDisposable interfaces
public class MyEnumerator: IEnumerator, IDisposable
{
int nIndex;
MyCollection collection;
public MyEnumerator(MyCollection coll)
{
collection = coll;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return (nIndex < collection.items.GetLength(0));
}
public int Current
{
get
{
return (collection.items[nIndex]);
}
}
// The current property on the IEnumerator interface:
object IEnumerator.Current
{
get
{
return (Current);
}
}
public void Dispose()
{
Console.WriteLine("In Dispose");
collection = null;
}
}
}
public class MainClass
{
public static void Main(string [] args)
{
MyCollection col = new MyCollection();
Console.WriteLine("Values in the collection are:");
// Display collection items:
foreach (int i in col)
{
Console.WriteLine(i);
}
}
}
浙公网安备 33010602011771号