c# - Call base method instead of override -
in c#, class a
contains public method foo()
processing , returns value. protected
method bar()
, in class a
performs same logic foo()
, followed additional processing, , returns value.
in order avoid duplicating code, bar()
calls foo()
, uses return intermediate value.
class { public virtual string foo() { string computedvalue; // compute value. return computedvalue; } protected string bar() { string computedvalue; string intermediatevalue = foo(); /// more processing create computedvalue intermediatevalue. return computedvalue; } }
class b
inherits a
, overrides foo()
. override calls base class implementation of bar()
.
class b : { public override string foo() { base.bar(); } }
this (of course) goes infinite loop until computer runs out of memory , yields stack overflow exception.
the obvious solution rewrite private foointernals
method contains guts of foo. foo , bar modified use results of method.
is there way force a's bar()
call a's foo()
instead of override?
(i'm being way clever here; goes against polymorphism. can't resist urge try pushing knowledge bit further.)
is there way force a's bar() call a's foo() instead of override?
not directly. simplest refactoring change foo
to:
public virtual string foo() { return fooimpl(); } private string fooimpl() { string computedvalue; // compute value. return computedvalue; }
then change bar
call fooimpl
instead of foo
.
(this meant in "most obvious solution" paragraph - missed on first reading, i'm afraid.)
fundamentally 1 of areas inheritance problematic. when 1 virtual method calls one, needs documented subclasses can avoid causing problems - though feels should implementation detail. it's sort of thing makes me prefer composition on inheritance - both reasonable options, of course.
Comments
Post a Comment