共用方式為


編譯器錯誤 CS0202

更新:2007 年 11 月

錯誤訊息

foreach 要求 'type.GetEnumerator()' 的傳回型別 'type' 必須有適合的公用 MoveNext 方法和公用 Current 屬性

用來啟用使用 foreach 陳述式的 GetEnumerator 函式無法傳回指標或陣列;它必須傳回可做為列舉值的類別執行個體。可做為列舉值的適當要求包括公用 Current 屬性和公用 MoveNext 方法。

注意事項:

在 C# 2.0 中,編譯器將自動產生 Current 和 MoveNext。如需詳細資訊,請參閱泛型介面 (C# 程式設計手冊) 中的程式碼範例。

下列範例會產生 CS0202:

// CS0202.cs

public class C1
{
   public int Current
   {
      get
      {
         return 0;
      }
   }

   public bool MoveNext ()
   {
      return false;
   }

   public static implicit operator C1 (int c1)
   {
      return 0;
   }
}

public class C2
{
   public int Current
   {
      get
      {
         return 0;
      }
   }

   public bool MoveNext ()
   {
      return false;
   }

   public C1[] GetEnumerator ()
   // try the following line instead
   // public C1 GetEnumerator ()
   {
      return null;
   }
}

public class MainClass
{
   public static void Main ()
   {
      C2 c2 = new C2();

      foreach (C1 x in c2)   // CS0202
      {
         System.Console.WriteLine(x.Current);
      }
   }
}