【发布时间】:2010-08-05 11:36:49
【问题描述】:
我认为这个问题最好通过一个例子来理解,所以我们开始吧:
public class Base {
// this method works fine
public void MethodA(dynamic input) {
// handle input
}
}
public class Derived: Base { // Derived was named Super in my original post
// This is also fine
public void MethodB(dynamic input) {
MethodA(input);
}
// This method does not compile and the compiler says:
// The call to method 'MethodA' needs to be dynamically dispatched,
// but cannot be because it is part of a base access expression.
// Consider casting the dynamic arguments or eliminating the base access.
public void MethodC(dynamic input) {
base.MethodA(input);
}
}
编译器明确指出方法 C 是无效的,因为它使用基访问来调用方法 A。但这是为什么呢?
在使用动态参数覆盖方法时如何调用基方法?
例如如果我想做什么:
public class Base {
// this method works fine
public virtual void MethodA(dynamic input) {
Console.WriteLine(input.say);
}
}
public class Derived: Base { // Derived was named Super in my original post
// this does not compile
public override void MethodA(dynamic input) {
//apply some filter on input
base.MethodA(input);
}
}
【问题讨论】: