最近开始学习 C# ,现在再学习里面的迭代器,在网上找了个例子,但是弄来有问题,在
class IterationSampleEnumerator
里面的values和startingPrint 会提示不可访问,因为它受保护级别限制问题代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace 迭代器
{
class Class1
{
static void Main(string[] args)
{
object[] test = new object[] { '1', '2', '3', 'a', 'b', 'c' };
EmunSample es = new EmunSample(test, 2);
foreach (object s in es)
{
Console.WriteLine(s + " 自己做的");
}
Console.ReadLine();
}
}
class EmunSample : IEnumerable
{
//定义迭代器内部的对象组合
public object[] irnu;
//定义迭代器开始迭代点
public Int32 startingpoint;
//构造参数传入集合
public EmunSample(object[] irnu, Int32 startingpoint)
{
this.irnu = irnu;
this.startingpoint = startingpoint;
}
/// <summary>
/// 从IEnumerable 集成的迭代方法
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return new IterationSampleEnumerator(this);
}
}
class IterationSampleEnumerator : IEnumerator
{
//迭代器对象
EmunSample parent;
//迭代器游标
Int32 position ;
//迭代器构造方法
internal IterationSampleEnumerator(EmunSample parent)
{
this.parent = parent;
position = -1;
}
//下一个方法
public bool MoveNext()
{
if (position != parent.irnu.Length)
{
position++;
}
return position < parent.irnu.Length;
}
//判断合法性方法
public object Current
{
get
{
if (position == -1 || position == parent.irnu.Length)
{
throw new InvalidOperationException();
}
//开始考虑自定义起点问题
Int32 index = position + parent.startingpoint;
//防止index大于集合长度
index %= parent.irnu.Length;
return parent.irnu[index];
}
}
//重置方法
public void Reset()
{
//将游标重置为-1
position = -1;
}
}
}
百度了下,有个帖子里面楼主解决了但是没回音,自己看了下
在IterationSample 里面的父类没有加public ,记得保存