当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用foreach语句遍历集合类型的方法

C#使用foreach语句遍历集合类型的方法

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

本文实例讲述了c#使用foreach语句遍历集合类型的方法。分享给大家供大家参考。具体如下:

这里演示如何实现可与 foreach 语句一起使用的集合类

using system;
using system.collections;
public class tokens: ienumerable
{
  private string[] elements;
  tokens(string source, char[] delimiters)
  {
   elements = source.split(delimiters);
  }
  // ienumerable 接口实现:
  public tokenenumerator getenumerator() // 非 ienumerable 版本
  {
   return new tokenenumerator(this);
  }
  ienumerator ienumerable.getenumerator() // ienumerable 版本
  {
   return (ienumerator) new tokenenumerator(this);
  }
  // 内部类实现 ienumerator 接口:
  public class tokenenumerator: ienumerator
  {
   private int position = -1;
   private tokens t;
   public tokenenumerator(tokens t)
   {
     this.t = t;
   }
   public bool movenext()
   {
     if (position < t.elements.length - 1)
     {
      position++;
      return true;
     }
     else
     {
      return false;
     }
   }
   public void reset()
   {
     position = -1;
   }
   public string current // 非 ienumerator 版本:类型安全
   {
     get
     {
      return t.elements[position];
     }
   }
   object ienumerator.current // ienumerator 版本:返回对象
   {
     get
     {
      return t.elements[position];
     }
   }
  }
  // 测试标记 tokenenumerator
  static void main()
  {
   tokens f = new tokens("this is a well-done program.", 
     new char [] {' ','-'});
   foreach (string item in f) // 要将 string 更改为 int
   {
     console.writeline(item);
   }
  }
}

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

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

相关文章:

验证码:
移动技术网