Compiler Error CS1579

foreach 语句不能对“type1”类型的变量进行操作,因为“type2”不包含“identifier”的公共定义

若要使用 foreach 语句循环访问某个集合,该集合必须满足以下要求:

在本示例中,foreach 无法循环访问集合,因为 MyCollection 集合中没有 publicGetEnumerator 方法。

下面的示例生成 CS1579。

// CS1579.cs
using System;
public class MyCollection 
{
   int[] items;
   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   // Delete the following line to resolve.
   MyEnumerator GetEnumerator()

   // Uncomment the following line to resolve:
   // public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Declare the enumerator class:
   public class MyEnumerator 
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public bool MoveNext() 
      {
         nIndex++;
         return(nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return(collection.items[nIndex]);
         }
      }
   }

   public static void Main() 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");
      foreach (int i in col)   // CS1579
      {
         Console.WriteLine(i);
      }
   }
}