编译器错误 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);
}
}
}