It looks to me that in using that in creating generic IEnumerables, you
lose polymorphic capabilities.
Consider this pseudo code:
abstract class BaseClass;
class DerivedClassSpe cialFunction1 : BaseClass
class DerivedClassSpe cialFunction2 : BaseClass
class Function1Implem entationA : DerivedClassSpe cialFunction1
class Function1Implem entationB : DerivedClassSpe cialFunction1
List<BaseClass> mylist = new List<BaseClass>
// assume the above list gets populated with a mix of the above classes
foreach (BaseClass item in mylist)
{
DerivedClassSpe cialFunction1 derivedItem = item as
DerivedClassSpe cialFunction1;
if (derivedItem != null)
{
derivedItem.Cal lSpecialFunctio n();
}
}
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<Der ivedClassSpecia lFunction1>
GetSpecialFunct ion1ClassesOnly ()
{
foreach (BaseClass item in mylist)
{
if (item is DerivedClassSpe cialFunction1) yield return item;
}
}
So, later if I use this enumerator in a foreach call like this:
foreach (DerivedClassSp ecialFunction1 item in
GetSpecialFunct ionClassesOnly( ))
{
item.CallSpecia lFunction();
}
This does not work correctly. Instead of calling the
Function1Implem entationA version of CallSpecialFunc tion(), it always
uses the DerivedClassSpe cialFunction 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