Поделиться через


Ошибка компилятора CS1640

Обновлен: Ноябрь 2007

Сообщение об ошибке

Оператор foreach не действует с переменными типа 'type', потому что он реализует несколько вариантов создания экземпляров интерфейса 'interface'. Попытайтесь выполнить приведение к конкретному варианту создания экземпляров интерфейса
foreach statement cannot operate on variables of type 'type' because it implements multiple instantiations of 'interface', try casting to a specific interface instantiation

Тип наследует от двух или нескольких экземпляров IEnumerator<T>, что означает, что уникального перечисление этого типа, которое может использоваться инструкцией foreach, не существует. Укажите тип IEnumerator<T> или используйте другую конструкцию цикла.

Пример

Следующий пример проводит к генерированию ошибки 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;
    }
}