Delen via


Compilerfout CS1579

foreach-instructie kan niet worden uitgevoerd op variabelen van het type 'type1' omdat 'type2' geen openbare definitie voor 'id' bevat

Als u een verzameling wilt herhalen met behulp van de foreach-instructie , moet de verzameling voldoen aan de volgende vereisten:

  • Het type moet een openbare parameterloze GetEnumerator methode bevatten waarvan het retourtype klasse, struct of interfacetype is.
  • Het retourtype van de methode moet een openbare eigenschap met de GetEnumerator naam Current en een openbare parameterloze methode bevatten met de naam MoveNext waarvan het retourtype is Boolean.

Opmerking

In het volgende voorbeeld wordt CS1579 gegenereerd omdat de MyCollection klasse niet de openbare GetEnumerator methode bevat:

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