Partager via


Erreur du compilateur CS1640

Mise à jour : novembre 2007

Message d'erreur

l'instruction foreach ne peut pas fonctionner sur des variables de type 'type', car elle implémente plusieurs instanciations de 'interface', essayez d'effectuer un cast en une instanciation d'interface spécifique
foreach statement cannot operate on variables of type 'type' because it implements multiple instantiations of 'interface', try casting to a specific interface instantiation

Le type hérite de deux instances d'IEnumerator<T> (ou davantage), ce qui signifie qu'il n'y a pas une énumération unique du type que foreach pourrait utiliser. Spécifiez le type d'IEnumerator<T> ou utilisez une autre construction de bouclage.

Exemple

L'exemple suivant génère l'erreur CS1640 :

// CS1640.cs

using System;
using System.Collections;
using System.Collections.Generic;

public class C : IEnumerable, IEnumerable<int>, IEnumerable<string>
{
    IEnumerator<int> IEnumerable<int>.GetEnumerator()
    {
        yield break;
    }

    IEnumerator<string> IEnumerable<string>.GetEnumerator()
    {
        yield break;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return (IEnumerator)((IEnumerable<string>)this).GetEnumerator();
    }
}

public class Test
{
    public static int Main()
    {
        foreach (int i in new C()){}    // CS1640

        // Try specifing the type of IEnumerable<T>
        // foreach (int i in (IEnumerable<int>)new C()){}
        return 1;
    }
}