c# - Apply generic visitor to generic derived class of non-generic base class -
currently have this:
public abstract class base {...} public class derived<t> : base {...} class visitor { public static void visit<t>(derived<t> d) { ... } }
my question is, given base
reference know derived
instance, how can apply visit
function object, using correct generic instantiation? understand answer involve type-checked dynamic downcast, make sure object isn't other type derived base, fine. assume answer involves reflection, fine, though i'd prefer if there way without reflection.
it's ok if answer involves abstract method on base
, derived
; have enough control of classes add that. @ end of day, need call generic function, correctly instantiated t
of derived type.
sorry if easy question; come c++ background, instinct use crtp or else that, isn't possible in c#.
edit:
here's example of need able do:
base getsomederivedinstance() { ...; return new derived<...>(); } var b = getsomederivedinstance(); // line needs work, though doesn't // need have exact call signature. requirement // instantiated generic invoked correctly. visitor.visit(b);
in opinion, answers involving double-dispatch , more classes going superior using reflection inheritance should you.
normally means defining 'accept' method on visitable class, calls correct visit method visitor.
class base { public virtual void accept(visitor visitor) { visitor.visit(this); // calls base overload. } } class derived<t> : base { public override void accept(visitor visitor) { visitor.visit(this); // calls derived<t> overload. } } public class visitor { public void visit(base @base) { ... } public void visit<t>(derived<t> derived) { ... } }
then can mentioned in question, small modification:
base b = createderived(); b.accept(new visitor());
if visit method static class can't change whatever reason, wrap dummy instance visitor class calls right static method.
Comments
Post a Comment