C#中foreach原理以及模拟的实现
作者:shichen2014 时间:2022-04-07 23:18:12
本文实例讲述了C#中foreach原理以及模拟的实现方法,分享给大家供大家参考。具体如下:
public class Person:IEnumerable //定义一个person类 并且 实现IEnumerable 接口 (或者不用实现此接口 直接在类 //里面写个GetEnumerator()方法)
{
string[] names = { "小杨", "科比布莱恩特", "凯文杜兰特", "卡门安东尼" }; //在Person类里面定义一个字符串数组,以便用来模仿对象的索引访问
public int Count { get { return names.Length; } } //可以通过对象访问此属性
public string this[int index] //定义一个索引器
{
get { return names[index]; }
}
public IEnumerator GetEnumerator()
{
return new MyClass(names); //实际上通过此方法就是返回一个可以实现循环的类的对象
// 用他的对象来移动索引
}
}
public class MyClass :IEnumerator
{
public MyClass(string[] names) //一个参数的构造函数,用来和要遍历的类的进行关联
{
name = names;
}
private string[] name; //用此字段来存放接收过来的数组
int index = -1;
public object Current //获取当前索引的元素的值
{
get
{
if (index<0) //准备状态是-1,开始循环了在MoveNext中加1
{
return null;
}
else
{
return name[index];
}
}
}
public bool MoveNext()
{
++index; //每调用此方法就将索引往下+1
if (index<name.Length)
{
return true;
}
else
{
return false;
}
}
public void Reset()
{
index=-1;
}
}
在主方法里面:
class Program
{
static void Main(string[] args)
{
Person p = new Person();
//for (int i = 0; i < p.Count; i++)
//{
// Console.WriteLine(p[i]);
//}
foreach (string item in p)
{
Console.WriteLine(item);
}
//实际执行foreach就相当于执行下面几句话:
Console.WriteLine("==================================================");
IEnumerator p1 = p.GetEnumerator();
while (p1.MoveNext())
{
string str=(string)p1.Current;
Console.WriteLine(str);
}
Console.ReadKey();
}
}
希望本文所述对大家的C#程序设计有所帮助。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
springboot2.0整合dubbo的示例代码
![](https://img.aspxhome.com/file/2023/5/78045_0s.png)
详解java中的PropertyChangeSupport与PropertyChangeListener
Java日常练习题,每天进步一点点(7)
![](https://img.aspxhome.com/file/2023/8/59978_0s.png)
Maven+Tomcat8 实现自动化部署的方法
Spring Security中使用authorizeRequests遇到的问题小结
![](https://img.aspxhome.com/file/2023/2/64952_0s.png)
java文字转语音播报功能的实现方法
Java8使用stream实现list中对象属性的合并(去重并求和)
![](https://img.aspxhome.com/file/2023/9/62379_0s.png)
java注解结合aspectj AOP进行日志打印的操作
![](https://img.aspxhome.com/file/2023/3/65783_0s.jpg)
C#实现顺序表(线性表)完整实例
Java Spring AOP之PointCut案例详解
对比Java中的Comparable排序接口和Comparator比较器接口
springboot用controller跳转html页面的实现
![](https://img.aspxhome.com/file/2023/1/75711_0s.png)
java开发线上事故理解RocketMQ异步精髓
![](https://img.aspxhome.com/file/2023/1/57501_0s.jpg)
JAVA 枚举单例模式及源码分析的实例详解
Windows系统中Java调用cmd命令及执行exe程序的方法
学习Winform文本类控件(Label、Button、TextBox)
![](https://img.aspxhome.com/file/2023/5/86985_0s.png)
IDEA 使用mybatis插件Free Mybatis plugin的步骤(推荐)
![](https://img.aspxhome.com/file/2023/8/72328_0s.jpg)
java equals函数用法详解
Java实现inputstream流的复制代码实例
SpringBoot使用Kaptcha实现验证码的生成与验证功能
![](https://img.aspxhome.com/file/2023/7/66977_0s.png)