当我使用类型为 TemplateA 的参数调用 EntryPoint 时,我总是收到异常,因为总是调用第一个重载。
我期望发生的是由于动态绑定(bind)而调用最具体的方法(第二个重载)。
知道为什么吗?
private object _obj;
public void EntryPoint(object p)
{
myFunc(p);
}
//first overload
private void myFunc(object container)
{
throw new NotImplementedException();
}
//second overload
private void myFunc(TemplateA template)
{
_obj = new ObjTypeA(template);
}
//third overload
private void myFunc(TemplateB template)
{
_obj = new ObjTypeB(template);
}
最佳答案
What I expected to happen is that the most specific method (second overload) will be called due to dynamic binding.
你在哪里看到动态绑定(bind)?变量的静态类型是object
。除非您直接对其 调用虚拟方法,否则不会发生动态调度。重载在编译时完全静态解析。
Eric Lippert 有一个相关的博客条目:Double Your Dispatch, Double Your Fun .
关于c# - 方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1183930/