コンパイラ エラー CS1579

更新 : 2007 年 11 月

エラー メッセージ

foreach ステートメントは、'type2' が '識別子' のパブリック定義を含んでいないため、型 'type1' の変数に対して使用できません。

コレクションを foreach ステートメントで反復処理するには、そのコレクションが次の要件を満たしていることが必要です。

使用例

この例では、publicGetEnumerator メソッドが MyCollection にないため、foreach はコレクションを反復処理できません。

次の例では 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);
      }
   }
}