Skip to content

Instantly share code, notes, and snippets.

@AlphaGit
Created February 7, 2012 17:48
Show Gist options
  • Save AlphaGit/1760972 to your computer and use it in GitHub Desktop.
Save AlphaGit/1760972 to your computer and use it in GitHub Desktop.
StackOverflow on GetEnumerator
public class TableCountryMappingCollection : ConfigurationElementCollection, IList<TableCountryMapping>
{
//...
IEnumerator<TableCountryMapping> IEnumerable<TableCountryMapping>.GetEnumerator()
{
foreach (var item in ((System.Collections.IEnumerable)this).Cast<TableCountryMapping>())
yield return item;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return base.GetEnumerator();
}
}
@andresmoschini
Copy link

El problema era que al utilizar foreach (var item in this) estabas accediendo al GetEnumerator() de TableCountryMappingCollection en lugar del de ConfigurationElementCollection. Esta es la correción:

public new IEnumerator<TableCountryMapping> GetEnumerator()
{
    foreach (TableCountryMapping item in (IEnumerable)this)
        yield return item;
}

@andresmoschini
Copy link

Con this.Select(x => x) o con ((System.Collections.IEnumerable)this).Cast<TableCountryMapping>() también estabas accediendo al GetEnumerator() de TableCountryMappingCollection ya que Linq accede al GetEnumerator() por reflection y no por polimorfismo como si hace el foreach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment