c# - "this" keyword type when called on an object of derived class from base class -
if have this:
class base { public void write() { if (this derived) { this.name();//calls name method of base class i.e. prints base ((derived)this).name();//calls derived method i.e prints derived } else { this.name(); } } public void name() { return "base"; } } class derived : base { public new void name() { return "derived"; } }
and use following code call it,
derived v= new derived(); v.write(); // prints base
then name
method of base class gets called. actual type of this
keyword in write
method? if of derived
type(as program control enters first if block in write
method) calling base name
method, , why explicit casting,(derived)this
, change call name
method of derived class?
this
of derived class type.
the reason why in call this.name();
calls base class name()
method because name
not defined virtual method, being linked in compile time when compiler knows nothing actual type of this
have @ point.
one more note regarding code above. in product code referring derived class base class explicitly bad practice breaks 1 of oop principles base class should not aware classes inherit it. however, assuming code above used c++ investigation of course ok.
Comments
Post a Comment