I want to do something like this:
class T : IEnumerable<string>, IEnumerable<int>
{
string [] _strings = new string [20];
int[] _ints = new int[20];
public T() { }
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
foreach (string str in _strings)
yield return str;
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
foreach (int i in _ints)
yield return i;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
//Using in code:
T t = new T();
foreach (int i in t)
//to do something
foreach (string str in t)
//to do stuff
I desire to know Is there a way to realize It or not. May be there are tricks ?
You’ve nearly managed to implement both interfaces – you just need to change the non-generic implementation to show which generic implementation you’re trying to delegate to. For example:
However, because you’re implementing more than one
IEnumerable<T>interface you’ll need to cast in the foreach loop to show which one to use:Personally I would strongly advise against doing this if possible though – it’ll cause a lot of confusion for people reading your code.
See section 8.8.4 of the C# language specification for details of how the compiler treats the expression to iterate over in a
foreachloop.(By using “normal” interface implementation for one of the interfaces you could provide a sort of “default” – but I don’t think that would really make it any better.)