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