In the following code, I would have expected calling a.Generate(v)
would have resulted in calling V.Visit(A a)
, since when Generate is called this
is of type A. Hoewever, it appears that this
is seen as being an Inter
instead.
Is it possible to have the intended behaviour without explicitly implementing the (identical) method in both A
and B
and only on the shared base class? If so, how can it be acheived?
using System;
using System.Diagnostics;
namespace Test {
class Base {}
class Inter: Base {
public virtual void Generate(V v) {
// `Visit(Base b)` and not `Visit(A a)` is called when calling
// A.Generate(v). Why?
v.Visit(this);
}
}
class A: Inter {}
class B: Inter {}
class V {
public void Visit(Base b) { throw new NotSupportedException(); }
public void Visit(A a) { Trace.WriteLine("a"); }
public void Visit(B b) { Trace.WriteLine("b"); }
}
class Program {
static void Main() {
V v = new V();
A a = new A();
B b = new B();
a.Generate(v);
b.Generate(v);
}
}
}
Edit
It was suggested in the answers that the code above is not polymorphic. I would object to that. V.Visit
is polymorphic.