Freigeben über


Compilerfehler CS1579

Aktualisiert: November 2007

Fehlermeldung

Eine foreach-Anweisung kann nicht für Variablen vom Typ "Typ1" verwendet werden, da "Typ2" keine öffentliche Definition für "Bezeichner" enthält.
foreach statement cannot operate on variables of type 'type1' because 'type2' does not contain a public definition for 'identifier'

Um eine Auflistung mit der foreach-Anweisung wiederholt zu durchlaufen, muss die Auflistung die folgenden Anforderungen erfüllen

Beispiel

In diesem Beispiel kann foreach nicht die Auflistung durchlaufen, weil keine public GetEnumerator-Methode in MyCollection vorhanden ist.

Im folgenden Beispiel wird CS1579 generiert:

// 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);
      }
   }
}