i trying implement ienumerable<turtle>
in class deriving base class implements ienumerable<animal>
.
why calling base.cast<turtle>()
(or linq method on base element) in method class turtle
fail compile?
it not possible replace base
this
results in stackoverflowexception
.
here minimal code sample replicate issue:
public interface ianimal {} public class animal : ianimal {} public class turtle : animal {} public class animalenumerable : ienumerable<animal> { list<animal> animals = new list<animal>(); ienumerator<animal> ienumerable<animal>.getenumerator() { return animals.getenumerator(); } ienumerator ienumerable.getenumerator() { return animals.getenumerator(); } } public class turtleenumerable : animalenumerable, ienumerable<turtle> { ienumerator<turtle> ienumerable<turtle>.getenumerator() { return base.cast<turtle>().getenumerator(); //fails "cannot resolve symbol cast" } }
for reason, replacing base.cast<turtle>().getenumerator();
this.oftype<animal>().cast<turtle>().getenumerator();
works without throwing stackoverflowexception
, have no idea why.
there numerous problems code given other answers into. want answer specific question:
why calling
base.cast<turtle>()
(or linq method on base element) in method classturtle
fail compile?
let's go specification, section 7.6.8.
a base-access used access base class members hidden named members in current class or struct.
are accessing base class member? no. extension method member of static class contains extension method, not base class.
a base-access permitted in block of instance constructor, instance method, or instance accessor.
you're fine here.
when base.i occurs in class or struct, must denote member of base class of class or struct.
again, cast<t>
not member of base class.
when base-access references virtual function member (a method, property, or indexer), determination of function member invoke @ run-time (§7.5.4) changed.
you not accessing virtual anything. extension methods static.
the function member invoked determined finding derived implementation of function member respect b (instead of respect run-time type of this, usual in non-base access). thus, within override of virtual function member, base-access can used invoke inherited implementation of function member.
so see purpose of base access is: to enable non-virtual dispatch virtual member overriden in current type, or to call base class member hidden new
member in current type. not trying use base
for, , therefore doomed failure. stop using base
off-label this. use when attempting non-virtual dispatch virtual member, or access hidden member.
Comments
Post a Comment