【发布时间】:2013-03-27 07:29:51
【问题描述】:
在下面的代码中,我预计调用 a.Generate(v) 会导致调用 V.Visit(A a),因为当调用 Generate 时,this 属于 A 类型。然而,似乎 this 被视为Inter 代替。
是否可以在不显式实现A 和B 中的(相同)方法且仅在共享基类上实现预期行为?如果可以,如何实现?
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);
}
}
}
编辑
答案中建议上面的代码不是多态的。我会反对。 V.Visit 是 polymorphic。
【问题讨论】:
-
嗯...我认为完成这项工作的唯一方法是在 A 和 B 中实现 Generate。
-
是的...我希望有另一种方式...
标签: c# polymorphism