当前位置: 移动技术网 > IT编程>开发语言>c# > C#中foreach原理以及模拟的实现

C#中foreach原理以及模拟的实现

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网