Kompilatorfel CS1579
foreach-instruktionen kan inte användas på variabler av typen "type1" eftersom "type2" inte innehåller någon offentlig definition för "identifierare"
Om du vill iterera genom en samling med foreach-instruktionen måste samlingen uppfylla följande krav:
- Dess typ måste innehålla en offentlig parameterlös
GetEnumerator
metod vars returtyp antingen är klass, struct eller gränssnittstyp. - Returtypen
GetEnumerator
för metoden måste innehålla en offentlig egenskap med namnetCurrent
och en offentlig parameterlös metod med namnetMoveNext
vars returtyp är Boolean.
Följande exempel genererar CS1579 eftersom MyCollection
klassen inte innehåller den offentliga GetEnumerator
metoden:
// 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);
}
}
}
Feedback om .NET
.NET är ett öppen källkod projekt. Välj en länk för att ge feedback: