代码中如何返回IEnumerator?
using System;
using System.Collections;
namespace ConsoleTest
{
class ColorEnumerator : IEnumerable
{
string[] Colors;//实现IEnumerator
int Position = -1;
public object Current
{
get
{
if (Position == -1)
throw new InvalidOperationException();
if (Position == Colors.Length)
throw new InvalidOperationException();
return Colors[Position];
}
}
public bool MoveNext()
{
if (Position < Colors.Length - 1)
{
Position++;
return true;
}
else
return false;
}
public void Reset() { Position = -1; }
public ColorEnumerator(string[] theColors)//构造函数
{
Colors = new string[theColors.Length];
for (int i = 0; i < theColors.Length; i++)
Colors[i] = theColors[i];
}
}
class MyColors : IEnumerable
{
//必须实现IEnumerable接口和实现方法,定义此类型为可枚举类型。
string[] Colors = new string[3] { "Red", "Yellow", "Blue" }; //定义一个string数组
public IEnumerator GetEnumerator()
{
//关键,必须实现的方法,返回为IEnumerator接口类型,为枚举数对象.通过它来实现另外的3个方法。
return new ColorEnumerator(Colors);//传入的参数为,本类的变量。
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("按任意键结束...");
Console.ReadKey();
}
}
}
以上是源代码,请问return new ColorEnumerator(Colors);这行代码中如何返回IEnumerator?谢谢!
using System.Collections;
namespace ConsoleTest
{
class ColorEnumerator : IEnumerable
{
string[] Colors;//实现IEnumerator
int Position = -1;
public object Current
{
get
{
if (Position == -1)
throw new InvalidOperationException();
if (Position == Colors.Length)
throw new InvalidOperationException();
return Colors[Position];
}
}
public bool MoveNext()
{
if (Position < Colors.Length - 1)
{
Position++;
return true;
}
else
return false;
}
public void Reset() { Position = -1; }
public ColorEnumerator(string[] theColors)//构造函数
{
Colors = new string[theColors.Length];
for (int i = 0; i < theColors.Length; i++)
Colors[i] = theColors[i];
}
}
class MyColors : IEnumerable
{
//必须实现IEnumerable接口和实现方法,定义此类型为可枚举类型。
string[] Colors = new string[3] { "Red", "Yellow", "Blue" }; //定义一个string数组
public IEnumerator GetEnumerator()
{
//关键,必须实现的方法,返回为IEnumerator接口类型,为枚举数对象.通过它来实现另外的3个方法。
return new ColorEnumerator(Colors);//传入的参数为,本类的变量。
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("按任意键结束...");
Console.ReadKey();
}
}
}
以上是源代码,请问return new ColorEnumerator(Colors);这行代码中如何返回IEnumerator?谢谢!
...全文
相关推荐
C# Language Specification 2.0.pdf
C# Language Specification 2.0.pdf
.NET软件工程师面试题
自己整理的面试题 1.面向对象的语言具有(继承)性、(多态)性、(封装)性。 2.能用foreach遍历访问的对象需要实现 (IEnumberable)接口或声明(GetEnumberator)方法的类型。 3.列举ADO.net中的五个主要对象(Command)、(Connection)、(DataReader)、(DataSet)、(DataAdapter)。 4.C#中的三元运算符是__(?:)__ 5.当整数a赋值给一个object对象时,整数a将会被__(装箱)___
C#自建类实现集合接口IEnumerable, IEnumerator
C#自建集合类MyArrayList实现集合接口IEnumerable, IEnumerator, 实现方法 inr add(object value),void Remove(object o), int Count, void Clear()
IEnumerator泛型函数调用方法
IEnumerator泛型函数调用方法
Unity.Blog.Understanding_IEnumerator:http 的示例代码
Unity.Blog.Understanding_IEnumerator 的文章示例代码。 执照 在许可下获得。


