IEnumerable接口与IEnumerator接口

网友投稿 233 2024-02-01


IEnumerable接口与IEnumerator接口

本文讲解"IEnumerable接口与IEnumerator接口",用于解决相关问题。

通过一个例子来看

-------------------------------------------------------Student.cs

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication6 {     public class Student:IEnumerable     {         //数组         public string[] s;         //索引器         public int i;         public Student(string[] str)//构造函数,初始化数组         {             s = str;         }         public IEnumerator GetEnumerator()//迭代器         {             return s.GetEnumerator();         }     } }

-------------------------------------------------------StiAll.cs

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication6 {     public class StiAll:IEnumerator     {         //student对象         Student s;         //游标         int i = -1;         public StiAll(Student ss)//构造函数,初始化student对象         {             this.s = ss;         }           public object Current//获取当前的项(只读属性)         {             get { return s.s[i]; }         }         public bool MoveNext()//将游标的位置向前移动         {             if (i<s.s.Length-1)//如果在s数组的长度范围之内就返回true             {                 i++;                 return true;             }             else             {                 return false;             }         }         public void Reset()//初始化游标         {             i = -1;         }     } }

-------------------------------------------------------主程序

Student s = new Student(new string[] { "吕蒙", "周泰", "黄盖" });//实例化Student对象             //第一种方式遍历             foreach (var item in s)             {                 Console.WriteLine(item);//输出吕蒙,周泰,黄盖             }             //第二种方式遍历             StiAll sa = new StiAll(s);             while (sa.MoveNext())             {                 Console.WriteLine(sa.Current);//输出吕蒙,周泰,黄盖             }             Console.ReadKey();

编程技术 和 程序设计

本文讲解"C# Monitor类的使用",用于解决相关问题。C#中, 通过System.Threading.Monitor类可以实现多线程中对某些代码块的同步访问,以确保数据的安全性。object obj=ne ...


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java接口有哪些形式
下一篇:浅析c# 接口
相关文章

 发表评论

暂时没有评论,来抢沙发吧~