Sdílet prostřednictvím


Postupy: Přístup ke třídě kolekce pomocí příkazu foreach (Průvodce programováním v C#)

Následující příklad kódu ukazuje, jak psát obecné kolekce třídy, který lze použít s foreach.Příklad definuje třídu string tokenizer.

[!POZNÁMKA]

V tomto příkladu představuje doporučené praxi pouze v případě, že třída obecnou kolekci nelze použít.Příklad implementace třídy typu bezpečné obecnou kolekci, která podporuje IEnumerable, viz Iterátory (C# and Visual Basic).

V příkladu následující kód používá segment Tokens na konec věty "Toto je ukázka věta." do tokenů pomocí třídy "" a "-" jako oddělovače.Kód poté zobrazí tyto tokeny pomocí foreach prohlášení.

Tokens f = new Tokens("This is a sample sentence.", new char[] {' ','-'});

// Display the tokens. 
foreach (string item in f)
{
    System.Console.WriteLine(item);
}

Příklad

Vnitřně Tokens třída používá pole k uložení tokeny.Protože matice IEnumerator a IEnumerable, ukázkový kód nelze použít pole výčtu metody (GetEnumerator, MoveNext, Reset, a Current) namísto jejich definování Tokens třídy.Definice metody, které jsou zahrnuty v příkladu vysvětlit, jak jsou definovány a co nemá každý.

using System.Collections;

// Declare the Tokens class. The class implements the IEnumerable interface. 
public class Tokens : IEnumerable
{
    private string[] elements;

    Tokens(string source, char[] delimiters)
    {
        // The constructor parses the string argument into tokens.
        elements = source.Split(delimiters);
    }

    // The IEnumerable interface requires implementation of method GetEnumerator. 
    public IEnumerator GetEnumerator()
    {
        return new TokenEnumerator(this);
    }


    // Declare an inner class that implements the IEnumerator interface. 
    private class TokenEnumerator : IEnumerator
    {
        private int position = -1;
        private Tokens t;

        public TokenEnumerator(Tokens t)
        {
            this.t = t;
        }

        // The IEnumerator interface requires a MoveNext method. 
        public bool MoveNext()
        {
            if (position < t.elements.Length - 1)
            {
                position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        // The IEnumerator interface requires a Reset method. 
        public void Reset()
        {
            position = -1;
        }

        // The IEnumerator interface requires a Current method. 
        public object Current
        {
            get
            {
                return t.elements[position];
            }
        }
    }


    // Test the Tokens class. 
    static void Main()
    {
        // Create a Tokens instance.
        Tokens f = new Tokens("This is a sample sentence.", new char[] {' ','-'});

        // Display the tokens. 
        foreach (string item in f)
        {
            System.Console.WriteLine(item);
        }
    }
}
/* Output:
    This
    is
    a
    sample
    sentence.  
*/

V jazyce C#, není nutné pro třídy kolekce implementovat IEnumerable a IEnumerator kompatibilní s foreach.Pokud má požadované třídy GetEnumerator, MoveNext, Reset, a Current členů, bude pracovat s foreach.Vynechání rozhraní má výhodu umožňuje definovat návratový typ pro Current je přesnější než Object.To zajišťuje bezpečnost typů.

Například můžete změňte následující řádky v předchozím příkladu.

// Change the Tokens class so that it no longer implements IEnumerable.
public class Tokens
{
    // . . .

    // Change the return type for the GetEnumerator method.
    public TokenEnumerator GetEnumerator()
    {   }

    // Change TokenEnumerator so that it no longer implements IEnumerator.
    public class TokenEnumerator
    {
        // . . .

        // Change the return type of method Current to string.
        public string Current
        {   }
    }
 }

Protože Current vrátí řetězec, kompilátor zjistit při nekompatibilní typ foreach prohlášení, jak je znázorněno v následujícím kódu.

// Error: Cannot convert type string to int.
foreach (int item in f)  

Nevýhodou vynecháním IEnumerable a IEnumerator je kolekce tříd je již interoperabilní s foreach prohlášení nebo odpovídající příkazy, jiných běžných jazyků runtime jazyka.

Viz také

Referenční dokumentace

Pole (Průvodce programováním v C#)

System.Collections.Generic

Koncepty

Průvodce programováním v C#

Další zdroje

Referenční dokumentace jazyka C#

Kolekce (C# and Visual Basic)