object - c# runtime polymorphism with abstract base class -
object - c# runtime polymorphism with abstract base class -
i trying clean existing code base, , having problem using generic reference name different derived classes of abstract class.
for instance:
public abstract class base<t> : utilities.commonrequiredobject { protected list<t> rawcontents = new list<t>(); . . public abstract void loadcontents(list<t> contents); // each class needs load , process differently protected list<t> contents; public virtual void dosomething() // default here mutual use. defined in each class specifics (if needed) { ... } public abstract list<t> functiontogetcontents(); } public class foo : base<string> { public override void dosomething() ... public override list<string> functiontogetcontents() ... } public class bar : base<byte> { public override void dosomething() ... public override list<byte> functiontogetcontents() ... }
main logic seek utilize mutual variable. want create new class use, want utilize in runtime polymorphic way. classes have mutual functionality, , have overrides needed, want able create instance, , utilize it:
ie: base<t> objecttouse;
this way, can refer objecttouse
in next code , phone call mutual methods. inherited mutual routines base of operations class, not sure if can utilize interface or not.
if(variable) { foo objecttouse = new foo(); } else { bar objecttouse = new bar(); } objecttouse.loadcontents(objecttouse.functiontogetcontents()); objecttouse.dosomething(); ...
edit: based on comments received (thanks 1 time again everyone) improve remove generic (base<t>
) , have classes of type base(), define objecttouse
base objecttouse;
believe.
this cannot done.
by utilizing reference requires generic type parameter, must give one. utilize dynamic
here type run-time evaluated, thats best get.
even utilizing template method pattern, need specify generic type argument. if want dosomething
method this, need promoted higher base of operations class (or interface) hold reference that type, , phone call (non-generic) function.
to comment, solution take this; refactor mutual code template method pattern within base of operations class. have "triggering" function non-generic inherited fellow member non-generic base of operations class (or interface). now, can hold reference type, , invoke template method cause other calls occur.
public void doawesomestuff() //inherited non-generic parent or interface { loadcontents(functiontogetcontents()); dosomething(); }
then:
idoesawesomestuff objecttouse = new foo(); objecttouse.doawesomestuff();
c# object polymorphism runtime
Comments
Post a Comment