foreach的秘密

class Program

{

static void Main(string[] args)

{

//创建Person的对象

Person p1=new Person();

//遍历p1因为实现了IEnumerable接口

foreach (var item in p1)

{

Console.WriteLine(item);

}

Console.ReadKey();

}

}

//实现了Ienumerable接口就可以遍历对象了

//实现IIndextor因为EnumeratorIndex是泛型类需要实现IIndextor接口

public class Person:IEnumerable,IIndextor

{

public string[] strs = new string[6];

public string this[int Index]

{

get { return strs[Index]; }

set { strs[Index] = value; }

}

public Person()

{

strs[0] = "3sfgew";

strs[1] = "322";

strs[2] = "34";

strs[3] = "3434";

strs[4] = "3ww";

strs[5] = "3sdfe";

}

public IEnumerator GetEnumerator()

{

//返回Ienumerator的实现类

return new EnumeratorIndex<Person>(this);

}

public int IndexLength

{

get { return strs.Length; }

}

}

//定义索引器的接口

public interface IIndextor

{

string this[int Index] { get; }

int IndexLength { get; }

}

public class EnumeratorIndex<T> : IEnumerator where T:IIndextor

{

T p1;

int Index;

//构造函数

public EnumeratorIndex(T p1)

{

//给必须的对象赋值

//Index的初始值必须是-1

Index = -1;

this.p1 = p1;

}

//返回当前的对象

public object Current

{

get { return p1[Index]; }

}

//使索引前进到下一个

public bool MoveNext()

{

if (Index < p1.IndexLength - 1)

{

Index++;

return true;

}

else

{

return false;

}

}

//初始化索引

public void Reset()

{

Index = -1;

}

}

最新文章

  1. JQuery easyUI DataGrid 创建复杂列表头(译)
  2. 自适应滤波原理及simulink
  3. 超酷HTML5 Canvas图表应用Chart.js自定义提示折线图
  4. [No000031]操作系统 Operating Systems 之Open the OS!
  5. ServiceManager: Permmission failure: android.permission.RECORD_AUDIO
  6. Ubuntu 安装 Xfce4 桌面
  7. JS复习
  8. [C++] socket -7 [邮槽]
  9. svm特征
  10. html5 中meta中 content=width=device-width注意
  11. Nexus 7 跳过网络验证
  12. php 生成mysql数据字典代码
  13. GitHub安装失败
  14. .NET Web开发之.NET MVC框架
  15. cnn 文章
  16. .net 程序集
  17. 去掉word页眉上横线的技巧
  18. MSSQL sqlserver系统函数教程分享
  19. Oracle SQL高级编程&mdash;&mdash;分析函数(窗口函数)全面讲解
  20. MySql中的约束

热门文章

  1. 【bzoj2330】: [SCOI2011]糖果 图论-差分约束-SPFA
  2. 关于spring xml文件中的xmlns,xsi:schemaLocation
  3. Mysql导入数据时-data truncated for column..
  4. TFS解锁命令
  5. 关于使用self.title文字不居中的解决办法
  6. CBoard 看板参数管理
  7. C语言学习总结(1)——结构体
  8. PyQt 5+qtDesigner
  9. python学习之路---day04
  10. C#多线程函数如何传参数和返回值