Compartir a través de


Error del compilador CS1579

Actualización: noviembre 2007

Mensaje de error

La instrucción foreach no puede funcionar en variables de tipo 'tipo1' porque 'tipo2' no contiene ninguna definición pública para 'identificador'
foreach statement cannot operate on variables of type 'type1' because 'type2' does not contain a public definition for 'identifier'

Para recorrer en iteración una colección utilizando la instrucción foreach, la colección debe cumplir los requisitos siguientes:

Ejemplo

En este ejemplo, foreach no puede recorrer en iteración la colección porque no hay un método GetEnumeratorpublic en MyCollection.

El código siguiente genera el error 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);
      }
   }
}