1

我有一个自定义配置部分,其中包含我使用从这个问题中获得的以下代码创建的集合:

public class GenericConfigurationElementCollection<T> : ConfigurationElementCollection, IEnumerable<T> where T : ConfigurationElement, new()
{
    List<T> _elements = new List<T>();

    protected override ConfigurationElement CreateNewElement()
    {
        T newElement = new T();
        _elements.Add(newElement);
        return newElement;
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return _elements.Find(e => e.Equals(element));
    }

    public new IEnumerator<T> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }
}

我使用以下属性实现了我的集合:

    [ConfigurationProperty("states")]
    [ConfigurationCollection(typeof(StateElement))]
    public GenericConfigurationElementCollection<StateElement> States
    {
        get
        {
            return (GenericConfigurationElementCollection<StateElement>)this["states"];
        }
    }

问题是,当我尝试使用 Parallel.ForEach 遍历集合时,如下所示

Parallel.ForEach<StateElement>(config.States.GetEnumerator(), state=> theState.StateStatus(state));

我收到以下错误:

The best overloaded method match for 'System.Threading.Tasks.Parallel.ForEach<States.Configuration.StateElement>(System.Collections.Generic.IEnumerable<States.Configuration.StateElement>, System.Action<States.Configuration.StateElement>)' has some invalid arguments   
Argument 1: cannot convert from 'System.Collections.Generic.IEnumerator<States.Configuration.StateElement>' to 'System.Collections.Generic.IEnumerable<States.Configuration.StateElement>'

最后一个让我难住了。无法从 IEnumerator 转换为 IEnumerable?

4

1 回答 1

0

尝试

config.States.Cast<StateElement>()

代替

config.States.GetEnumerator()
于 2013-02-07T16:42:28.947 回答