It looks to me that in using that in creating generic IEnumerables, you
lose polymorphic capabilities.
Consider this pseudo code:
abstract class BaseClass;
class DerivedClassSpecialFunction1 : BaseClass
class DerivedClassSpecialFunction2 : BaseClass
class Function1ImplementationA : DerivedClassSpecialFunction1
class Function1ImplementationB : DerivedClassSpecialFunction1
List<BaseClass> mylist = new List<BaseClass>
// assume the above list gets populated with a mix of the above classes
foreach (BaseClass item in mylist)
{
DerivedClassSpecialFunction1 derivedItem = item as
DerivedClassSpecialFunction1;
if (derivedItem != null)
{
derivedItem.CallSpecialFunction();
}
}
This allows me to iterate through a list of objects all subclassed from
the same absrtact class and then, for only specific types, call some
function. The function called is the correct function for the instance
type.
I then tried to create an IEnumerator method to try to clean this up a
bit (hoping to avoid testing for the right type everytime (and also
checking for null).
My iterator looked something like this:
public IEnumerator<DerivedClassSpecialFunction1>
GetSpecialFunction1ClassesOnly()
{
foreach (BaseClass item in mylist)
{
if (item is DerivedClassSpecialFunction1) yield return item;
}
}
So, later if I use this enumerator in a foreach call like this:
foreach (DerivedClassSpecialFunction1 item in
GetSpecialFunctionClassesOnly())
{
item.CallSpecialFunction();
}
This does not work correctly. Instead of calling the
Function1ImplementationA version of CallSpecialFunction(), it always
uses the DerivedClassSpecialFunction version.
Is there a way to do what I want and still use custom enumerators? I
want to selectively filter on type, but retain the polymorphic
abilities of subclasses from that type.
Thanks!
Mike