Compartir a través de


Error del compilador CS1579

La instrucción foreach no puede funcionar en variables de tipo 'type1' porque 'type2' no contiene ninguna definición pública para 'identifier'

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

  • Su tipo debe incluir el método público sin parámetros GetEnumerator cuyo tipo de valor devuelto es clase, estructura o tipo de interfaz.
  • El tipo de valor devuelto del método GetEnumerator debe contener la propiedad pública llamada Current y un método público sin parámetros denominado MoveNext cuyo tipo de valor devuelto es Boolean.

Ejemplo

En el ejemplo siguiente se genera CS1579 porque la clase MyCollection no contiene el método público GetEnumerator:

// 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.Length);  
      }  
  
      public int Current => 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);  
      }  
   }  
}