日期:2009-07-15  浏览次数:20486 次

启用 Foreach
   
    许多用户希望能够使用 foreach 遍历我的列表。为此,我需要在类中实现 Ienumerable,并定义一个单独的用于实现 Ienumerable 的类。第一步,测试:

   
  [Test]
  public void TestForeach()
  {
  IntegerList list = new IntegerList();
  list.Add(5);
  list.Add(10);
  list.Add(15);
  list.Add(20);
   
  ArrayList items = new ArrayList();
   
  foreach (int value in list)
  {
  items.Add(value);
  }
   
  Assertion.AssertEquals("Count", 4, items.Count);
  Assertion.AssertEquals("index 0", 5, items[0]);
  Assertion.AssertEquals("index 1", 10, items[1]);
  Assertion.AssertEquals("index 2", 15, items[2]);
  Assertion.AssertEquals("index 3", 20, items[3]);
  }
   
  我还通过 IntegerList 实现 IEnumerable:
   
  public IEnumerator GetEnumerator()
  {
  return null;
  }
   
   
    运行测试时,此代码生成异常。为了正确地实现此功能,我将使用一个嵌套类作为枚举器。
   
  class IntegerListEnumerator: IEnumerator
  {
  IntegerList list;
  int index = -1;
   
  public IntegerListEnumerator(IntegerList list)
  {
  this.list = list;
  }
  public bool MoveNext()
  {
  index++;
  if (index == list.Count)
  return(false);
  else
  return(true);
  }
  public object Current
  {
  get
  {
  return(list[index]);
  }
  }
  public void Reset()
  {
  index = -1;
  }
  }
   
   
    此类将一个指针传递给 IntegerList 对象,然后只返回此对象中的元素。
   
    这样,便可以对列表执行 foreach 操作,但遗憾的是 Current 属性属于对象类型,这意味着每个值将被装箱才能将其返回。此问题可采用一种基于模式的方法加以解决,此方法酷似当前方法,但它通过 GetEnumerator() 返回一个真正的类(而非 IEnumerator),且此类中的 Current 属性为 int 类型。
   
    然而执行此操作后,我要确保在不支持该模式的语言中仍然可以使用这种基于接口的方法。我将复制编写的上一个测试并修改 foreach 以转换为接口:
   
    foreach (int value in (IEnumerable) list)
   
    只需少许改动,列表即可在两种情况下正常运行。请查看代码样例以获取更多细节和更多测试。
   
    几点说明
   
    为本月的专栏文章编写代码和文字大约花了我一个小时的时间。事先编写测试的优点就是您可以对在类中添加哪些内容以使测试通过有一个清楚的认识,从而简化代码的编写。
   
    如果要进行小型、递增的测试,则使用此方法最合适。我鼓励您在小型项目中使用此方法。事先测试开发是所谓的“敏捷方法”的一部分。