自写一个模仿Dictionary与Foreach的实现及心得总结

2019-05-20 13:18:52于海丽


面试题中经常会问Foreach实现了什么接口这个问题很好回答,那我们能不能自己模仿实现Foreach呢?
c、Foreach内部原理:IEnumerable接口 自己实现IEnumerable

using System.Collections;//引入IEnumerable所在命名空间
namespace IEnumerater {
class MyList : IEnumerable {//实现接口IEnumerable 它就一个IEnumerator声明枚举器的方法
ArrayList ary = new ArrayList();
public void Add(string name) {
ary.Add(name);
}
//自己写索引器 形式类似属性 作用类似枚举 方便快捷的方式 访问集合中的元素
public string this[ int index] {//int类型
get {
return ary[index].ToString();
} //index>ary.Count时超出索引界限
//set { }
}
public int this[ string name] {//string类型 通过name查找索引 参数类型自己决定 返回类型自己决定
get {
for(int i = 0; i < ary.Count; i++) {
if(ary[i] == name) {
return i;
}
}
return -1;
}
}
public IEnumerator GetEnumerator() {//IEnumerator F12跳转定义这里可以发现foreach只允许读取数据,而不能修改数据
for(int i = 0; i < ary.Count; i++) {
yield return ary[i].ToString();// yield关键字 可以看到 实现IEnumerator(枚举器)接口中MoveNext(指向下一条)方法 和Current(获取当前元素 因为只有get 所以可以理解为什么foreach不能修改值的原因了) 以及Reset重置索引
}
}
}
}

d、调用自己的IEnumerable

using System;
namespace IEnumerater {
class Program {
static void Main(string[] args) {
//自己写一个类 实现了IEnumerable接口的getEnumerator()方法 就可以实现foreach的操作
MyList mylist = new MyList();
mylist.Add( "wanghao");//调用自己的add(string)方法
mylist.Add( "nihao");
mylist.Add( "buhao");
Console.WriteLine(mylist[1]);//使用自己的索引
Console.WriteLine(mylist["nihao" ].ToString());
foreach(string item in mylist) {
Console.WriteLine(item);
//item = "hello"; 不能使用foreach改变值
}
Console.Read();
}
}
}

总结:
如果一个类进行foreach的话,该类必须实现IEnumerable,集合要支持foreach方式的遍历,必须实现IEnumerable接口(还要以某种方式返回实现了IEnumerator 的对象)