I think I understand why IEnumerable<T> inherit from IEnumerable, after reading the post:
Why does IEnumerable<T> inherit from IEnumerable?
However, I am not sure how best to implement the non-generic method when appling 2 generic interfaces? Here is an example of the code I am writting:
public interface IComponentA { /* ... Interface A Code ... */ }
public interface IComponentB { /* ... Interface B Code ... */ }
public class ComponentModel: IEnumerable<IComponentA>, IEnumerable<IComponentB>
{
public ComponentModel() { }
private List<IComponentA> ListOfComponentA = new List<IComponentA>();
private List<IComponentB> ListOfComponentB = new List<IComponentB>();
// ... Some public methods to add and remove components (for A and B).
IEnumerator<IComponentA> IEnumerable<IComponentA>.GetEnumerator()
{
return ListOfComponentA.GetEnumerator();
}
IEnumerator<IComponentB> IEnumerable<IComponentB>.GetEnumerator()
{
return ListOfComponentB.GetEnumerator();
}
// The fact that IEnumerable<T> inherits from the non-generic IEnumerable
// now means I have to deal with this.
IEnumerator IEnumerable.GetEnumerator()
{
// Throwing a NotImplementedException is probably not a good idea
// so what should I put in here?
throw new NotImplementedException();
}
}
Suggestions of what to put in the non-generic method are welcome please.
I probably wouldn’t do that, myself. It can be confusing for a user to have the enumerator enumerate over different things depending on the interface reference calling it, and of course the issue of what the generic returns as well.
Instead, you could just expose a read-only-ish version of the lists as an iterator:
By using the
Skip(0)you return an iterator, and it prevents them from casting back toList<IComponentA>and modifying theListout from under you.You could also use a
ReadOnlyCollectionof course, but those are kinda clunky since they throw when you try to do mutating ops.So now, you can iterate over either:
Also, IF A and B component lists always have the same length, you could have an enumerator over a
Tupleof them in .NET 4.0 and using the Linq Zip() method: