当前位置: 移动技术网 > IT编程>开发语言>c# > C#中IEnumerable接口用法实例分析

C#中IEnumerable接口用法实例分析

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

本文实例讲述了c#中ienumerable接口用法。分享给大家供大家参考。具体分析如下:

枚举数可用于读取集合中的数据,但不能用于修改基础集合。

最初,枚举数定位在集合中第一个元素前。reset 方法还会将枚举数返回到此位置。在此位置上,current 属性未定义。因此,在读取 current 的值之前,必须调用 movenext 方法将枚举数提前到集合的第一个元素。

在调用 movenext 或 reset 之前,current 返回同一对象。movenext 将 current 设置为下一个元素。

如果 movenext 越过集合的末尾,枚举数就会被放置在此集合中最后一个元素的后面,且 movenext 返回 false。当枚举数位于此位置时,对 movenext 的后续调用也返回 false。如果对 movenext 的最后一次调用返回 false,则 current 为未定义。若要再次将 current 设置为集合的第一个元素,可以调用 reset,然后再调用 movenext。

只要集合保持不变,枚举数就保持有效。如果对集合进行更改(如添加、修改或删除元素),则枚举数将失效且不可恢复,而且其行为是不确定的。

枚举数没有对集合的独占访问权;因此,从头到尾对一个集合进行枚举在本质上不是一个线程安全的过程。若要确保枚举过程中的线程安全,可以在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

下面的代码示例演示如何实现自定义集合的 ienumerable 接口。在此示例中,没有显式调用但实现了 getenumerator,以便支持使用 foreach(在 visual basic 中为 for each)。此代码示例摘自 ienumerable 接口的一个更大的示例。

using system;
using system.collections;
public class person
{
 public person(string fname, string lname)
 {
  this.firstname = fname;
  this.lastname = lname;
 }
 public string firstname;
 public string lastname;
}
public class people : ienumerable
{
 private person[] _people;
 public people(person[] parray)
 {
  _people = new person[parray.length];
  for (int i = 0; i < parray.length; i++)
  {
   _people[i] = parray[i];
  }
 }
 ienumerator ienumerable.getenumerator()
 {
  return (ienumerator) getenumerator();
 }
 public peopleenum getenumerator()
 {
  return new peopleenum(_people);
 }
}
public class peopleenum : ienumerator
{
 public person[] _people;
 // enumerators are positioned before the first element
 // until the first movenext() call.
 int position = -1;
 public peopleenum(person[] list)
 {
  _people = list;
 }
 public bool movenext()
 {
  position++;
  return (position < _people.length);
 }
 public void reset()
 {
  position = -1;
 }
 object ienumerator.current
 {
  get
  {
   return current;
  }
 }
 public person current
 {
  get
  {
   try
   {
    return _people[position];
   }
   catch (indexoutofrangeexception)
   {
    throw new invalidoperationexception();
   }
  }
 }
}
class app
{
 static void main()
 {
  person[] peoplearray = new person[3]
  {
   new person("john", "smith"),
   new person("jim", "johnson"),
   new person("sue", "rabon"),
  };
  people peoplelist = new people(peoplearray);
  foreach (person p in peoplelist)
   console.writeline(p.firstname + " " + p.lastname);
 }
}
/* this code produces output similar to the following:
 *
 * john smith
 * jim johnson
 * sue rabon
 *
 */

希望本文所述对大家的c#程序设计有所帮助。

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

相关文章:

验证码:
移动技术网